Preferred Python idiom for handling non-existing dictionary keys and why?

Quentin Crain czrpb at yahoo.com
Fri Oct 10 15:21:23 EDT 2003


Hello All!

Damn! Of course! 

thanks!! Quentin

--- Matt Goodall <matt at pollenation.net> wrote:
> 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
> 
> 


=====
-- Quentin Crain

------------------------------------------------
I care desperately about what I do.
Do I know what product I'm selling? No.
Do I know what I'm doing today? No.
But I'm here and I'm gonna give it my best shot.
  -- Hansel

__________________________________
Do you Yahoo!?
The New Yahoo! Shopping - with improved product search
http://shopping.yahoo.com





More information about the Python-list mailing list