For this simple Dictionary -
the Key 1 and Value "apple" always print as "1: False"
is there a reason for this I've overlooked?
$ cat dict.py
pairs = {1: "apple",
"orange": [2, 3, 4],
True: False,
None: "True",
}
print(pairs)
*$ python3.8 dict.py
{1: False, 'orange': [2, 3, 4], None: 'True'}
thanks
The
bool
type in Python is a subtype ofint
whereTrue
equals the number1
andFalse
equals the number0
:When the values are hashed, they also result in the respectively same value:
Now, since dictionary keys are based on hash and object equality (hash equality is used first to find possibly equal keys fast, and then they are compared through equality), two values that result in the same hash and are equal will result in the same “slot” of the dictionary.
You can also see this if you create a custom type that also has this behavior:
While this explains the behavior, I do agree that it can be somewhat confusing. As such I would recommend not to use dictionary keys of different types so that you don’t run into such a situation.