即使我检查dict中是否存在密钥,我也会收到一个密钥错误:
def foo(d):
if (('element' in d.keys()) & (d['element'] == 1)):
print "OK"
foo({})
在documentation我们可以阅读:
表达式x和y首先计算x;如果x为假,则其值为 回;否则,评估y并得到结果值 返回。
有人能解释一下这种行为吗?
答案 0 :(得分:5)
&
是“按位和”,and
是逻辑“和”运算符,它们不是一回事。
您应该使用and
,并且还可以删除不需要的括号以便于阅读。
您甚至不必调用keys
方法:
if 'element' in d and d['element'] == 1: