Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionary breaking the laws of python [duplicate]

When I do:

>>> d={True:'yes',1:'no',1.0:'maybe'}
>>> d

I receive an output of:

>>> {True:'maybe'}

It's not only that some of my keys are deleted but also the value it was holding changed.

Why is True given priority over another bool keys?

like image 593
Ritesh Avatar asked Jun 15 '18 04:06

Ritesh


People also ask

Is duplicates allowed in dictionary Python?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.

What happens when duplicate keys encountered during assignment in dictionary?

When duplicate keys are encountered during the assignment, the value will be the last assigned one. Keys must be immutable. This means you can use strings, numbers, or tuples as dictionary keys, but something like ['key'] is not allowed.

Does Set allow duplicate keys Python?

However, there are a few unique characteristics that define a set and separate it from other data structures: A set does not hold duplicate items. The elements of the set are immutable, that is, they cannot be changed, but the set itself is mutable, that is, it can be changed.


1 Answers

The three keys True, 1 and 1.0 compare equal to each other and all have the same hash (try hash(True), hash(1) and hash(1.0) in the Python REPL), so they all correspond to the same slot in the dictionary. The last value to be set wins - 'maybe' in this case.

Note that if the keys weren't equal, they would be stored separately even if they hashed to the same slot in the dictionary.

like image 173
babbageclunk Avatar answered Nov 11 '22 03:11

babbageclunk