A Counterintuitive Thing About Python Dictionaries

...which many python programmers get confused with.

Despite adding 4 distinct keys to a Python dictionary, can you tell why it only preserves two of them?

Here’s why.

In Python, dictionaries find a key based on the equivalence of hash (computed using hash()), but not identity (computed using id()).

In this case, there’s no doubt that 1.0, 1, and True inherently have different datatypes and are also different objects. This is shown below:

Yet, as they share the same hash value, the dictionary considers them as the same keys.

But did you notice that in the demonstration, the final key is 1.0, while the value corresponds to the key True.

This is because, at first, 1.0 is added as a key and its value is 'One (float)'. Next, while adding the key 1, python recognizes it as an equivalence of the hash value.

Thus, the value corresponding to 1.0 is overwritten by 'One (int)', while the key (1.0) is kept as is.

Finally, while adding True, another hash equivalence is encountered with an existing key of 1.0. Yet again, the value corresponding to 1.0, which was updated to 'One (int)' in the previous step, is overwritten by 'One (bool)'.

I am sure you may have already guessed why the string key ‘1’ is retained.

👉 Tell me you liked this post by leaving a heart react 🤍.

👉 If you love reading this newsletter, feel free to share it with friends!

Find the code for my tips here: GitHub.

I like to explore, experiment and write about data science concepts and tools. You can read my articles on Medium. Also, you can connect with me on LinkedIn and Twitter.

Reply

or to participate.