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 dict
I think the second example is what you should go for unless this code makes sense:
try:
A["foo"] = B["foo"]
A["bar"] = B["bar"]
A["baz"] = B["baz"]
except KeyError:
pass
Keep in mind that code will abort as soon as there is a key that isn't in B
. If this code makes sense, then you should use the exception method, otherwise use the test method. In my opinion, because it's shorter and clearly expresses the intent, it's a lot easier to read than the exception method.
Of course, the people telling you to use update
are correct. If you are using a version of Python that supports dictionary comprehensions, I would strongly prefer this code:
updateset = {'foo', 'bar', 'baz'}
A.update({k: B[k] for k in updateset if k in B})