Unhashable Type Python Error Explained: How To Fix It — Codefather

Claudio Sabato
7 min readApr 24, 2021

Have you ever seen the message “TypeError: unhashable type” when running your Python program? Do you know what to do to fix it?

The message “TypeError: unhashable type” appears in a Python program when you try to use a data type that is not hashable in a place in your code that requires hashable data. For example, as an item of a set or as a key of a dictionary.

This error can occur in multiple scenarios and in this tutorial we will analyse few of them to make sure you know what to do when you see this error.

Let’s fix it now!

Unhashable Type ‘Dict’ Python Error

To understand when this error occurs let’s replicate it in the Python shell.

We will start from a dictionary that contains one key:

>>> country = {"name": "UK"}
>>> country
{'name': 'UK'}

Now add a second item to the dictionary:

>>> country["capital"] = "London"
>>> country
{'name': 'UK', 'capital': 'London'}

All good so far, but here is what happens if by mistake we use another dictionary as key:

>>> info = {"language": "english"}
>>> country[info] = info["language"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'

The error unhashable type: ‘dict’ occurs because we are trying to use a dictionary as key of a dictionary item. By definition a dictionary key needs to be hashable.

What does it mean?

When we add a new key / value pair to a dictionary, the Python interpreter generates a hash of the key. To give you an idea of how a hash looks like let’s have a look at what the hash() function returns.

>>> hash("language")
-79422224077228785
>>> hash({"language": "english"})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'

You can see that we got back a hash for a string but when we tried to pass a dictionary to the hash function we got back the same “unhashable type” error we have seen before.

--

--

Claudio Sabato

Claudio Sabato is an IT expert with over 15 years of professional experience in Python/Bash programming, Linux Systems Administration and IT Systems Design.