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.