I came across code which I somehow find 'odd'.
var = None
try:
var = mydict[a][b]
except:
pass
I'm not very comfortable with using try-except for checking dict key, when obviously there is an if-else sequence to handle the same situation.
var = None
if a in mydict:
if b in mydict[a]:
var = mydict[a][b]
Is there any 'obvious' advantage/disadvantage of using one approach over the other?
Exception handling is generally much slower than an if statement. With the presence of nested dictionaries, it is easy to see why the author used an exception statement. However, the following would work also.
var = mydict.get(a,{}).get(b,None)
if var is None:
print("Not found")
else:
print("Found: " + str(var))
The use of get on the dict object returns a default value when the key is not present.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With