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.
Check out Sourcery, an automated code refactoring tool for Python to make your code more elegant, concise, and pythonic.
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.