1

I have a dictionary my_dict1, which contains a key 'Error' I also have another dictionary my_dict2 that either has multiple keys, or is empty. I want to have an if statement that checks whether my_dict1['Error'] is False and check if my_dict2 has any content in it. The code is as follows:

my_dict1 = {'Error': False}
my_dict2 = {'somekey': True}

if my_dict1['Error'] == False:
    if len(my_dict2) > 0:
        print('ok')
else:
    print('no')

This code results in 'ok' as expected.

if my_dict1['Error'] == False & len(my_dict2)> 0:
    print('ok')
else:
    print('no')

This results in 'no'. Am I understanding the & statement wrong?

C.Acarbay
  • 424
  • 5
  • 17

2 Answers2

2

The error originates from the precedence of the operators. Your expression is equivalent to:

my_dict1['Error'] == (False & len(my_dict2)) > 0

Now since False & 1 will result in 0, since False acts as 0, and the bitwise and-ing of 0 and 1 is 0.

The expression my_dict['Error'] == 0 > 0 is False. The my_dict['Error'] == 0 will succeed, but 0 > 0 is of course False.

If you want to check two conditions, you should use the and operator, like:

if my_dict1['Error'] == False and len(my_dict2) > 0:
    print('ok')
else:
    print('no')

or more Pythonic:

if not my_dict1['Error'] and my_dict2:
    print('ok')
else:
    print('no')

The two are not entirely the same since not my_dict['Error'] will succeed, given the truthiness of the corresponding value is True. If the items map on bools, then the two are equivalent.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
1

Am I understanding the & statement wrong?

Unfortunately, yes I think so. & is bitwise AND, where logical AND is called and in Python.

For more information about the differences between logical and bitwise operators, see this page: https://wiki.python.org/moin/BitwiseOperators

Morten Jensen
  • 5,818
  • 3
  • 43
  • 55
  • That is not per se the problem, since `True & False`, etc. just act like a logical `and`. – Willem Van Onsem Jul 13 '19 at 10:46
  • @WillemVanOnsem I agree. As you correctly point out in the comments, the problem seems to stem from operator precedence - that is your point, no? I quoted the part about `&` vs `and` since that is a common mistake as well :) – Morten Jensen Jul 13 '19 at 11:46