- Daily Dose of Data Science
- Posts
- You Can Add a List As a Dictionary's Key (Technically)!
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.
Find the code for my tips here: GitHub.
Reply