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
There is also a third way that avoids both exceptions and double-lookup, which can be important if the lookup is expensive:
value = B.get("blah", None)
if value is not None:
A["blah"] = value
In case you expect the dictionary to contain None
values, you can use some more esoteric constants like NotImplemented
, Ellipsis
or make a new one:
MyConst = object()
def update_key(A, B, key):
value = B.get(key, MyConst)
if value is not MyConst:
A[key] = value
Anyway, using update()
is the most readable option for me:
a.update((k, b[k]) for k in ("foo", "bar", "blah") if k in b)