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?
The straight answer is NO. You can not have duplicate keys in a dictionary in Python.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With