-0.8 C
New York
Wednesday, February 21, 2024

TypeError unhashable type ‘dict’

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)


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'


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)


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


Related Articles

Latest Articles