TypeError: Unhashable Type 'Dict' Exception in Python
Last Updated :
24 Apr, 2025
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)
Output{(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])
OutputDictionary 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)])
OutputDictionary is : {'name': 'shraman', ('age',): 'DOB'}
Element is : DOB
Similar Reads
Handle Unhashable Type List Exceptions in Python
Python, with its versatile and dynamic nature, empowers developers to create expressive and efficient code. However, in the course of Python programming, encountering errors is inevitable. One such common challenge is the "Unhashable Type List Exception". In this article, we will dive deep into the
3 min read
How to Add Values to Dictionary in Python
The task of adding values to a dictionary in Python involves inserting new key-value pairs or modifying existing ones. A dictionary stores data in key-value pairs, where each key must be unique. Adding values allows us to expand or update the dictionary's contents, enabling dynamic manipulation of d
3 min read
Python | Type conversion in dictionary values
The problem of conventional type conversion is quite common and can be easily done using the built-in converters of python libraries. But sometimes, we may require the same functionality in a more complex scenario vis. for keys of list of dictionaries. Let's discuss certain ways in which this can be
4 min read
How to Update a Dictionary in Python
This article explores updating dictionaries in Python, where keys of any type map to values, focusing on various methods to modify key-value pairs in this versatile data structure. Update a Dictionary in PythonBelow, are the approaches to Update a Dictionary in Python: Using with Direct assignmentUs
3 min read
Unpack Dictionary In Python
Unpacking a dictionary in Python means extracting its values and assigning them to variables, often in a more structured or readable way. For example, given a dictionary d = {"name": "Bob", "age": 22, "major": "Computer Science"}, you can unpack its values into separate variables like a = "Bob", b =
3 min read
How to Add User Input To A Dictionary - Python
The task of adding user input to a dictionary in Python involves taking dynamic data from the user and storing it in a dictionary as key-value pairs. Since dictionaries preserve the order of insertion, we can easily add new entries based on user input.For instance, if a user inputs "name" as the key
3 min read
Unpacking Dictionary Keys into Tuple - Python
The task is to unpack the keys of a dictionary into a tuple. This involves extracting the keys of the dictionary and storing them in a tuple, which is an immutable sequence.For example, given the dictionary d = {'Gfg': 1, 'is': 2, 'best': 3}, the goal is to convert it into a tuple containing the key
2 min read
How to Store Values in Dictionary in Python Using For Loop
In this article, we will explore the process of storing values in a dictionary in Python using a for loop. As we know, combining dictionaries with for loops is a potent technique in Python, allowing iteration over keys, values, or both. This discussion delves into the fundamentals of Python dictiona
3 min read
Set from Dictionary Values - Python
The task is to extract unique values from a dictionary and convert them into a set. In Python, sets are unordered collections that automatically eliminate duplicates. The goal is to extract all the values from the dictionary and store them in a set.For example, given a dictionary like d = {'A': 4, '
3 min read
Python - Test if all Values are Same in Dictionary
Given a dictionary, test if all its values are the same. Input : test_dict = {"Gfg" : 8, "is" : 8, "Best" : 8} Output : True Explanation : All element values are same, 8. Input : test_dict = {"Gfg" : 8, "is" : 8, "Best" : 9} Output : False Explanation : All element values not same. Method #1: Using
7 min read