Python: if key in dict vs. try/except

Posted by LeeMobile on Stack Overflow See other posts from Stack Overflow or by LeeMobile
Published on 2010-12-22T18:48:38Z Indexed on 2010/12/22 18:54 UTC
Read the original article Hit count: 172

Filed under:
|

I have a question about idioms and readability, and there seems to be a clash of Python philosophies for this particular case:

I want to build dictionary A from dictionary B. If a specific key does not exist in B, then do nothing and continue on.

Which way is better?

try:
    A["blah"] = B["blah"]
except KeyError:
    pass

or

if "blah" in B:
    A["blah"] = B["blah"]

"Do and ask for forgiveness" vs. "simplicity and explicitness".

Which is better and why?

© Stack Overflow or respective owner

Related posts about python

Related posts about idioms