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

Quentin Crain czrpb at yahoo.com
Fri Oct 10 12:32:35 EDT 2003


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"?

Thanks!!

  Quentin


=====
-- 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