TypeError: Unhashable Type ‘Dict’ Exception in Python
In Python, the “Type Error” is an exception and is raised when an object’s data type is incorrect during an operation. In this article, we will see how we can handle TypeError: Unhashable Type ‘Dict’ Exception in Python.
What is TypeError: Unhashable Type ‘Dict’ Exception in Python
In Python, certain data types are hashable, meaning their values don’t change during their lifetime. These hashable objects can be used as keys in dictionaries or elements in sets because their hash value is constant. However, dictionaries themselves are not hashable because they are mutable, meaning their content can be modified after creation.
When you attempt to use a dictionary as a key in another dictionary or as an element in a set, you’ll encounter the TypeError: Unhashable Type 'Dict'
exception.
Why does TypeError: Unhashable Type ‘Dict’ Exception occur?
Below are some of the reason due to which TypeError: Unhashable Type ‘Dict’ Exception error occurs in Python:
Nested Dictionaries
In this example, the TypeError: Unhashable Type 'Dict'
occurs when attempting to use a dictionary containing another dictionary as a key (new_dict = {dictionary: 'some_value'}
). Dictionaries are unhashable due to their mutability, leading to this exception.
Python3
dictionary = { 'key' : { 'nested_key' : 'value' }} new_dict = {dictionary: 'some_value' } |
Output:
Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 2, in <module>
new_dict = {dictionary: 'some_value'}
TypeError: unhashable type: 'dict'
Using a Dictionary in a Set
In this example, the TypeError: Unhashable Type 'Dict'
arises when attempting to create a set (set_of_dicts
) containing dictionaries directly. Sets require hashable elements, and dictionaries, being mutable, result in this error.
Python3
set_of_dicts = {{ 'key' : 'value' }, { 'key2' : 'value2' }} |
Output:
Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 1, in <module>
set_of_dicts = {{'key': 'value'}, {'key2': 'value2'}}
TypeError: unhashable type: 'dict'
Dictionary as a Key
In this example, a TypeError: Unhashable Type 'Dict'
is triggered as the code attempts to use a dictionary ({'name':'shraman'}
) as a key in another dictionary (my_dict={{'name':'shraman'}:24}
). Dictionaries, due to their mutability, cannot be hashed and used as keys directly.
Python3
# code my_dict = {{ 'name' : 'shraman' }: 24 } |
Output:
Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 2, in <module>
my_dict={{'name':'shraman'}:24}
TypeError: unhashable type: 'dict'
Solution for TypeError: Unhashable Type ‘Dict’ Exception in Python
Below are some of the solution for TypeError: Unhashable Type ‘Dict’ Exception in Python:
Use Immutable Types for Keys
In this example, the code creates a new dictionary (new_dict
) using a tuple (1, 'example')
as a hashable key and associates it with the nested_dict
. The print(new_dict)
statement displays the resulting dictionary.
Python3
nested_dict = { 'key' : 'value' } new_dict = {( 1 , 'example' ): nested_dict} print (new_dict) |
{(1, 'example'): {'key': 'value'}}
Typecasting into Frozenset
In this example, the code first typecasts the dictionary temp
into a frozenset
using frozenset(temp.items())
and then creates a new dictionary my_dict
with "name": "shraman"
as one key-value pair and the frozen set key
as another. The subsequent statements print the entire dictionary and access the element associated with the key
.
Python3
temp = { 'age' : 24 } #typecasting into frozenset key = frozenset (temp.items()) my_dict = { "name" : "shraman" ,key: 'DOB' } print ( "Dictionary is : " ,my_dict) # accessing the element print ( "Element is : " ,my_dict[key]) |
Dictionary is : {'name': 'shraman', frozenset({('age', 24)}): 'DOB'} Element is : DOB
Typecasting into Tuple
In this example, the code typecasts the dictionary temp
into a tuple using tuple(temp)
and creates a new dictionary my_dict
with "name": "shraman"
as one key-value pair and the tuple tuple(temp)
as another. The subsequent statements print the entire dictionary and access the element associated with the tuple key.
Python3
temp = { 'age' : 24 } # typecasting into tuple my_dict = { "name" : "shraman" , tuple (temp): 'DOB' } print ( "Dictionary is : " , my_dict) # accessing the element print ( "Element is : " , my_dict[ tuple (temp)]) |
Dictionary is : {'name': 'shraman', ('age',): 'DOB'} Element is : DOB