Discover more from Daily Dose of Data Science
"How" Python Prevents Us from Adding a List as a Dictionary's Key?
Exploring the technical reason.
What happens when we add a list as a dictionary’s key in Python?
We all know that Python raises an error.
Nothing new here. Everyone knows this.
But I think very few folks question the technical reason behind this.
Why is a list unhashable?
How is this implemented in practice?
If needed, how can we make our custom class objects unhashable because, by default, we can add any custom class object as a dictionary’s key, as shown below:
Let’s understand this today!
First, we must understand that EVERYTHING in Python is an object instantiated from some class:
List, tuple, dictionary, etc. are class objects.
Int, float, and string are class objects.
Functions are class objects.
In fact, even classes are also objects.
Adding an object as a dictionary’s key is like hashing the object.
Thus, whenever we add an object as a dictionary’s key, Python invokes the
__hash__() magic method of that object’s class.
Now, the implementation of
__hash__() magic method for classes of int, tuple, string, etc., allows its objects to be hashable.
However, the List class raises an error:
That is why whenever we add a list as a dictionary’s key, Python raises an error:
Thus, if needed, we can use the same idea on our custom classes and make its object unhashable. This is shown below:
Now, if we add its objects to a dictionary, Python will raise an error:
Now you have the complete information (conceptual and practical) on why some objects can be added as a dictionary’s key while some cannot.
👉 Over to you: What are some other core yet overlooked concepts in Python?
👉 If you liked this post, don’t forget to leave a like ❤️. It helps more people discover this newsletter on Substack and tells me that you appreciate reading these daily insights. The button is located towards the bottom of this email.
Thanks for reading!
Mind doing me a favor?
If you find the information presented in this newsletter useful and it helps you get better every day, I would love it if you could share your experience with others:
I am eager to read your reviews.
Latest full articles
If you’re not a full subscriber, here’s what you missed last month:
To receive all full articles and support the Daily Dose of Data Science, consider subscribing:
👉 If you love reading this newsletter, feel free to share it with friends!