Skip to content Skip to sidebar Skip to footer

Python: Try-except Vs If-else To Check Dict Keys

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 obvio

Solution 1:

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)

ifvaris 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.

Solution 2:

Just to note that in this scenario you can go for:

var = mydict.get(a, {}).get(b)

Solution 3:

One disadvantage arises from the fact that the 2 snippets are not equal, the first is a blanket statement which says that no matter what happens, stay quite.

To make them equal, modify the first snippet to catch just the KeyError :

var = Nonetry:
  var = mydict[a][b]
except KeyError:
  pass

As they stand, the second snippet will crash if something other than KeyError happens, the first one will keep going, and that is perhaps inviting more problems.

Post a Comment for "Python: Try-except Vs If-else To Check Dict Keys"