Python Error : TypeError: unhashable type: ‘dict’ – Resolved

python @ Freshers.in

The error TypeError: unhashable type: 'dict' in Python typically occurs when you attempt to use a dictionary as a key in another dictionary, or when you try to add a dictionary to a set. This is because dictionaries are mutable and thus unhashable in Python. Hashable objects in Python are those that have a fixed hash value for their entire lifetime, which dictionaries do not, as their contents can change.

Here are a couple of common scenarios where this error might occur:

1. Using a Dictionary as a Key in Another Dictionary

Dictionaries require their keys to be hashable. Since dictionaries are mutable, using them as keys is not allowed.

Example of the Issue:

my_dict = {}
inner_dict = {'key': 'value'}
my_dict[inner_dict] = 'some value'  # This will raise TypeError

2. Adding a Dictionary to a Set

Sets, like dictionary keys, also require their elements to be hashable. Therefore, adding a dictionary to a set will raise the same error.

Example of the Issue:

my_set = set()
inner_dict = {'key': 'value'}
my_set.add(inner_dict)  # This will raise TypeError

Resolving the Issue

To resolve this error, you can use immutable types (like tuples) as keys in dictionaries or elements in sets. If you need to use the data from a dictionary, consider converting it into a hashable type.

Example Solution:

my_dict = {}
inner_dict = {'key': 'value'}
# Convert the dictionary to a hashable type (like a tuple of tuples)
hashable_key = tuple(inner_dict.items())
my_dict[hashable_key] = 'some value'

This approach converts the dictionary into a tuple of tuples (which is hashable), allowing it to be used as a key in another dictionary. Remember that this conversion is one-way, and you’ll need to convert it back if you need to modify the dictionary later.

Author: user