Python: try-except vs if-else to check dict keys

走远了吗. 提交于 2021-01-28 02:31:52

问题


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?


回答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)

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.




回答2:


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

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



回答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 = 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.



来源:https://stackoverflow.com/questions/22128399/python-try-except-vs-if-else-to-check-dict-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!