Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

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

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 = None
try:
  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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top