Discover more from Daily Dose of Data Science
You Can Add a List As a Dictionary's Key (Technically)!
But it does not mean you should!
Python raises an error whenever we add a list as a dictionary's key. But do you know the technical reason behind it? Here you go.
Firstly, understand that everything in Python is an object instantiated from some class. Whenever we add an object as a dict's key, Python invokes the __𝐡𝐚𝐬𝐡__ function of that object's class.
While classes of int, str, tuple, frozenset, etc. implement the __𝐡𝐚𝐬𝐡__ method, it is missing from the list class. That is why we cannot add a list as a dictionary's key.
Thus, technically if we extend the list class and add this method, a list can be added as a dictionary's key.
While this makes a list hashable, it isn't recommended as it can lead to unexpected behavior in your code.
Share this post on LinkedIn: Post Link.
Thanks for reading Daily Dose of Data Science! Subscribe for free to learn something new about Python and Data Science every day.
Find the code for my tips here: GitHub.