Python:try-except与if-else检查dict键 [英] Python: try-except vs if-else to check dict keys

查看:52
本文介绍了Python:try-except与if-else检查dict键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了以某种方式找到奇数"的代码.

I came across code which I somehow find 'odd'.

var = None
try:
  var = mydict[a][b]
except:
  pass

我很不习惯使用 try-except 来检查 dict 键,当显然有一个 if-else 序列要处理相同的情况.

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?

推荐答案

异常处理通常比if语句慢得多.由于嵌套字典的存在,很容易看出为什么作者使用了异常语句.但是,以下方法也可以.

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

当键不存在时,在 dict 对象上使用 get 会返回默认值.

The use of get on the dict object returns a default value when the key is not present.

这篇关于Python:try-except与if-else检查dict键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆