hayj hayj - 4 months ago 6x
Python Question

If statement ordering and key error python

Here I get a key error even I check if the key exists in the dict :

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


In the documentation we can read :

The expression x and y first evaluates x; if x is false, its value is
returned; otherwise, y is evaluated and the resulting value is

Can anybody explain me this behavior?


& is "bitwise and", and is the logical "and" operator, they are not the same thing.

You should use and, and you can also remove the unneeded parenthesis for readability.

You also don't even have to call the keys method:

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