I'm trying to get familiar with the best practices of Python. According to the Zen of Python it's easier to ask forgiveness than to ask for permission, however, it also says that flat is better than nested and readability counts. How would you deal with this:
I have 3 dictionaries. I have a key, and I want to test if the key is in a dictionary. The key will only be in one of them. Depending on which dictionary it's in, I want to do different stuff.
Using try/except, I come to the following solution:
try:
val = dict1[key]
except KeyError:
try:
val = dict2[key]
except KeyError:
try:
val = dict3[key]
except KeyError:
do_stuff_key_not_found()
else:
do_stuff_dict3()
else:
do_stuff_dict2()
else:
do_stuff_dict1()
According to Python's EAFP principle this would be the way to go, but it looks cluttered, and is not very readable.
A simpler solution would be:
if key in dict1:
val = dict1[key]
do_stuff_dict1()
elif key in dict2:
val = dict2[key]
do_stuff_dict2()
elif key in dict3:
val = dict3[key]
do_stuff_dict3()
else:
do_stuff_key_not_found()
What is the more Pythonic way of handling a case like this? Should I stick to the EAFP principle, or is flat and readability more important?