[PYTHON] Behavior when 0, 1, False, True is used for the dictionary (dict) key

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 as0 and Truehas the same hash value as1`.

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

Behavior when 0, 1, False, True is used for the dictionary (dict) key
[For beginners] Unexpected behavior if "\" is included when setting the path in Python
Import audit.log into Splunk and check the behavior when Splunk is started for the first time
When a character string of a certain series is in the Key of the dictionary, the character string is converted to the Value of the dictionary.
How to turn the for statement when there are multiple values for one key in the dictionary
How Python __dict__ is used
What is the interface for ...
What is Python? What is it used for?
Check the behavior when assigning Python
[python] What is the sorted key?
What is the python underscore (_) for?
Why is cross entropy used for the objective function of the classification problem?