The Python TypeError: unhashable type: 'dict'
usually occurs when trying to hash a dictionary, which is an unhashable object. For example, using a dictionary as a key in another dictionary will cause this error. This is because dictionaries only accept hashable data types as a key.
Only immutable objects such as strings, integers and tuples are hashable since they have a single unique value that never changes. Hashing such objects always produces the same result, so they can be used as keys for dictionaries.
TypeError: Unhashable Type: 'Dict' Example
Here’s an example of a Python TypeError: unhashable type: 'dict'
thrown when a dictionary is used as the key for another dictionary:
my_dict = {1: 'A', {2: 'B', 3: 'C'}: 'D'}
print(my_dict)
Since a dictionary is not hashable, running the above code produces the following error:
File "test.py", line 1, in <module>
my_dict = {1: 'A', {2: 'B', 3: 'C'}: 'D'}
TypeError: unhashable type: 'dict'
How to Fix TypeError: Unhashable Type: 'Dict'
The Python TypeError: unhashable type: 'dict'
can be fixed by casting a dictionary to a hashable object such as tuple before using it as a key in another dictionary:
my_dict = {1: 'A', tuple({2: 'B', 3: 'C'}): 'D'}
print(my_dict)
In the example above, the tuple()
function is used to convert the dictionary to a tuple. The above code runs successfully and produces the correct output:
{1: 'A', (2, 3): 'D'}
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!