Daily Dose of Data Science

Share this post

You Can Add a List As a Dictionary's Key (Technically)!

www.blog.dailydoseofds.com

You Can Add a List As a Dictionary's Key (Technically)!

But it does not mean you should!

Avi Chawla
Mar 5, 2023
4
2
Share

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.

4
2
Share
Previous
Next
2 Comments
Dr. Amaka Charity Nwigwe
Mar 5Liked by Avi Chawla

Great

Expand full comment
Reply
Dr. Amaka Charity Nwigwe
Mar 5Liked by Avi Chawla

Great

Expand full comment
Reply
Top
New
Community

No posts

Ready for more?

© 2023 Avi Chawla
Privacy ∙ Terms ∙ Collection notice
Start WritingGet the app
Substack is the home for great writing