Online Tutorials & Training Materials | STechies.com
Register Login

TypeError unhashable type 'dict'

06 May 2020 12:29 pm || 0

If you are handling dictionaries containing keys and values, you might have encountered the program error "typeerror unhashable type 'dict'". This means that you are trying to hash an unhashable object. In simple terms, this error occurs when your code tries to hash immutable objects such as a dictionary. The solution to this problem is to convert the dictionary into something that is hashable.

In this article, we will look into the details of the error and its quick fix.

TypeError unhashable type 'dict'

Look at the piece of code mentioned below:

Error Example:

# Pyton Program
my_dictionary = {'Red':'Apple','Green':'Mango',{'Red':'Apple','Green':'Mango'}:'Banana'}
print('Dictionary :',my_dictionary)

Output:

Traceback (most recent call last):
File "pyprogram.py", line 1, in <module>
my_dictionary = {'Red':'Apple','Green':'Mango',{'Red':'Apple','Green':'Mango'}:'Banana'}
TypeError: unhashable type: 'dict'

Solution

To fix this error, you can convert the dictionary into a hashable object like 'tuple' and then use it as a key for a dictionary as shown below

Correct Code:

# Python Program
my_dictionary = {'Red':'Apple','Green':'Mango',tuple({'Red':'Apple','Green':'Mango'}):'Banana'}
print('Dictionary :',my_dictionary)

Output:

Dictionary : {'Red': 'Apple', 'Green': 'Mango', ('Red', 'Green'): 'Banana'}