Preferred Python idiom for handling non-existing dictionary keys and why?
Matt Goodall
matt at pollenation.net
Fri Oct 10 15:16:09 EDT 2003
Quentin Crain wrote:
>Hello again All!
>
>(First, I would like to mention I did try to google
>for the answer here!)
>
>Say I am populating a dictionary with a list and
>appending. I have written it thusly:
>
> d={}
> for (k,v) in somedata():
> try:
> d[k].append(v)
> except KeyError:
> d[k]=[v]
>
>I could have written:
>
> d={}
> for (k,v) in somedata():
> if (k in d):
> d[k].append(v)
> else:
> d[k]=[v]
>
>
>Which is perferred and why? Which is "faster"?
>
I assume from the above code that somedata returns a sequence of (key,
value) pairs, where a key may appear more than once, and you are trying
to collect all the values for each key?
Dictionary objects have a very useful method, setdefault, to help with
this sort of problem. I would write the above as:
>>> somedata = (('a',1),('b',2),('a',3),('c',4))
>>> d={}
>>> for k,v in somedata:
... d.setdefault(k,[]).append(v)
...
>>> d
{'a': [1, 3], 'c': [4], 'b': [2]}
Cheers, Matt
--
Matt Goodall, Pollenation Internet Ltd
w: http://www.pollenation.net
e: matt at pollenation.net
More information about the Python-list
mailing list