missing? dictionary methods
Ron
radam2 at tampabay.rr.com
Mon Mar 21 10:00:56 EST 2005
On 21 Mar 2005 08:21:40 GMT, Antoon Pardon <apardon at forel.vub.ac.be>
wrote:
>Well at least I find them missing.
>
>For the moment I frequently come across the following cases.
>
>1) Two files, each with key-value pairs for the same dictionary.
>However it is an error if the second file contains a key that
>was not in the first file.
>
>In treating the second file I miss a 'set' method.
>dct.set(key, value) would be equivallent to dct[key] = value,
>except that it would raise a KeyError if the key wasn't
>already in the dictionary.
>
>
>2) One file with key-value pairs. However it is an error
>if a key is duplicated in the file.
>
>In treating such files I miss a 'make' method.
>dct.make(key, value) would be equivallent to dct[key] = value.
>except that it would raise a KeyError if the key was
>already in the dictionary.
>
>
>What do other people think about this?
There is a has_key(k) method that helps with these.
Adding these wouldn't be that hard and it can apply to all
dictionaries with any data.
class newdict(dict):
def new_key( self, key, value):
if self.has_key(key):
raise KeyError, 'key already exists'
else:
self[key]=value
def set_key( self, key, value):
if self.has_key(key):
self[key]=value
else:
raise KeyError, 'key does not exist'
d = newdict()
for x in list('abc'):
d[x]=x
print d
d.new_key('z', 'z')
d.set_key('a', 'b')
print d
Which is faster? (has_key()) or (key in keys())?
More information about the Python-list
mailing list