如果语句排序和键错误python

hay*_*ayj -1 python dictionary if-statement keyerror

在这里我得到一个关键错误,即使我检查密钥是否存在于dict中:

def foo(d):
    if (('element' in d.keys()) & (d['element'] == 1)):
        print "OK"

foo({})
Run Code Online (Sandbox Code Playgroud)

文档中我们可以阅读:

表达式x和y首先计算x; 如果x为false,则返回其值; 否则,将评估y并返回结果值.

任何人都能解释一下这种行为吗?

Dee*_*ace 6

&是"按位和", and是逻辑"和"运算符,它们不是一回事.

你应该使用and,你也可以删除不需要的括号以便于阅读.

您甚至不必调用该keys方法:

if 'element' in d and d['element'] == 1:

  • 或者缩写为`if d.get('element'):`因为get会自动返回`None`(这是假的). (2认同)
  • 也许 `if d.get('element') == 1:` 来保留 `if` 语句的另一部分 (2认同)