0

Python's version is 3.

In Python’s Interpreter in Mac's terminal (console), I tried defining a couple of Dicts but found that all the second elements in those Dicts were always missing. See the code below:

>>> dictOne = {True: 'real', 1: 'one', 'two': 2}
>>> dictOne
{True: 'one', 'two': 2}

>>> dictTwo = {1: 'one', True: 'real', 'two': 2}
>>> dictTwo
{1: 'real', 'two': 2}

>>> dictThree = {1: 'one', True: 'real', False: 'fake', 'two': 2}
>>> dictThree
{1: 'real', False: 'fake', 'two': 2}

Boolean and Integer values seem to interfere with each other. What happened?

marcel
  • 77
  • 1
  • 4
  • 16
  • 1
    The keys in dictionaries are hashed in the internal data structure of the dictionary. If you try `print(hash(1.0))`, `print(hash(1))` and `print(hash(True))`, you'll get the same hash. Since dictionaries cannot have duplicate keys, the kv pair that remains is the last you set on the dictionary. – Alexandre Juma Dec 05 '18 at 02:28
  • You should also post the python version you're using to make the question clear. It also seems that it has been answered a number of times: https://stackoverflow.com/questions/52402133/true-and-1-and-1-0-evaluated-to-be-same-in-python-dictionaries – Alexandre Juma Dec 05 '18 at 02:32

1 Answers1

3

True and 1 mean the same thing to Python. (True is basically bool(1), and True == 1 evaluates to True)

Python dicts don't allow duplicate keys, and True and 1 are considered duplicates.

EDIT: Alexandre Juma gave a nice explanation of this. Essentially, dict keys are hashed, and hash(1) and hash(True) return the same thing.

iz_
  • 15,923
  • 3
  • 25
  • 40