a = {1 : 4}
print(4 in a) # case 1: False
a = {1 : 's'}
print('s' in a) # case 2: False
a = {1 : None}
print(None in a) # case 3: False
a = {1: True}
print(True in a) # case 4: True
so my question is why except the forth case all returns False ?
Membership testing is done against dictionaries' "keys", not values. For values you can do:
a = {1: 4}
print(4 in a.values())
But remember that it does a linear search as opposed to keys which is O(1).
For last case:
bool
is a subclass of int
and True
is equal to 1
. (Their hashes are of course the same)
Basically the same effect as:
s = {1, True}
print(len(s)) # 1
and
a = {1: 10}
print(a[True]) # 10