Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 808
Neo Avatar asked Aug 08 '26 22:08

Neo


1 Answers

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.

like image 146
Eric Urban Avatar answered Aug 11 '26 11:08

Eric Urban



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!