How Python Prevents Us from Adding a List as a Dictionary's Key?

Exploring the technical reason.

We all know that Python raises an error when we add a list as a dictionary’s key:

But have you ever wondered how exactly this is implemented in practice? How Python prevents us from adding a list as a dictionary’s key?

This is important to know because in Python, if we define a custom class, then by default, its objects can be added as a dictionary’s key, as shown below:

This behavior may not be desired at times.

Let’s understand the internal mechanisms 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.

Here’s a full deep dive into Python OOP if you want to learn more about advanced OOP in Python: Object-Oriented Programming with Python for Data Scientists.

👉 Over to you: What are some other core yet overlooked concepts in Python?

Thanks for reading!

In case you missed it

I unlocked the following three deep dives recently. Today is the last day that they will remain open.

These are a must-read if you want to build core ML skills in a beginner-friendly way.

Are you preparing for ML/DS interviews or want to upskill at your current job?

Every week, I publish in-depth ML deep dives. The topics align with the practical skills that typical ML/DS roles demand.

Join below to unlock all full articles:

Here are some of the top articles:

Join below to unlock all full articles:

👉 If you love reading this newsletter, share it with friends!

👉 Tell the world what makes this newsletter special for you by leaving a review here :)

Reply

or to participate.