A Hashable object can be used for the Python dictionary (dict) key, and the hash value is used as the key.
Python's bool
type is implemented as a subclass of the ʻint type, where
Falsehas the same hash value as
0 and
Truehas the same hash value as
1`.
>>> hash(0)
0
>>> hash(False)
0
>>> hash(1)
1
>>> hash(True)
1
Now let's see what happens when we use 0
, 1
, False
, True
as dictionary keys.
>>> d = { 0: 'zero', True: 'true' }
>>> d
{0: 'zero', True: 'true'}
>>> d[0]
'zero'
>>> d[True]
'true'
>>> d[False]
'zero'
>>> d[1]
'true'
I also got False
and 1
which are not in the dictionary.
Since the hash values are the same, it is a natural behavior.
Let's assign it to the dictionary.
>>> d
{0: 'zero', True: 'true'}
>>> d[False] = 'false'
>>> d[1] = 'one'
>>> d
{0: 'false', True: 'one'}
The key remains 0
and True
, and the values have been updated to 'false'
and 'one'
.
It turns out that the key uses the value from the first assignment and the value is the last assigned value. Not surprisingly, it was an interesting result.
>>> d = { 0: 'zero', True: 'true', 1: 'one', False: 'false'}
>>> d
{0: 'false', True: 'one'}
Recommended Posts