-1

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"

foo({})

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 returned.

Can anybody explain me this behavior?

hayj
  • 1,159
  • 13
  • 21

1 Answers1

6

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

DeepSpace
  • 78,697
  • 11
  • 109
  • 154