hayj hayj - 1 year ago 127
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?

Answer Source

& 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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download