`if key in dict` vs. `try/except` - which is more readable idiom? `if key in dict` vs. `try/except` - which is more readable idiom? python python

`if key in dict` vs. `try/except` - which is more readable idiom?


Exceptions are not conditionals.

The conditional version is clearer. That's natural: this is straightforward flow control, which is what conditionals are designed for, not exceptions.

The exception version is primarily used as an optimization when doing these lookups in a loop: for some algorithms it allows eliminating tests from inner loops. It doesn't have that benefit here. It has the small advantage that it avoids having to say "blah" twice, but if you're doing a lot of these you should probably have a helper move_key function anyway.

In general, I'd strongly recommend sticking with the conditional version by default unless you have a specific reason not to. Conditionals are the obvious way to do this, which is usually a strong recommendation to prefer one solution over another.


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)


From what I understand, you want to update dict A with key,value pairs from dict B

update is a better choice.

A.update(B)

Example:

>>> A = {'a':1, 'b': 2, 'c':3}>>> B = {'d': 2, 'b':5, 'c': 4}>>> A.update(B)>>> A{'a': 1, 'c': 4, 'b': 5, 'd': 2}>>>