typeerror: unhashable type: dict

As a Python developer, one of the common errors you may have encountered is “TypeError: unhashable type: ‘dict’” error message when working with dictionaries.

In this article, we will explain to you what the error message means, why it occurs, and provide solutions to fix it.

Before we proceed to the “typeerror: unhashable type: ‘dict” error message, let’s first know the meaning of hashability in Python.

What is Hashability in Python?

In Python, hashability refers to the ability of an object to be hashed.

Hashing is the process of converting an object into a different integer value, which is used to compare and store objects in a collection such as a dictionary or set.

What Does “TypeError: unhashable type: ‘dict” Mean?

Now that we already know the meaning of hashability, let’s discuss the “typeerror unhashable type ‘dict’” error message.

This error message typically occurs if you are trying to use a dictionary as a key in another dictionary or as an element in a set.

Since dictionaries are unhashable, it is cannot be used as keys in a dictionary or as elements in a set.

For example, let’s say we have two dictionaries:

mydict1 = {'a': 1, 'b': 2}
mydict2 = {'c': 3, 'd': 4}
mydict2[mydict1] = 5

If we are trying to use mydict1 as a key in mydict2, we’ll get the “typeerror unhashable type dict” error message:

Output:

C:\Users\Dell\PycharmProjects\pythonProject\venv\Scripts\python.exe C:\Users\Dell\PycharmProjects\pythonProject\main.py
Traceback (most recent call last):
File “C:\Users\Dell\PycharmProjects\pythonProject\main.py”, line 3, in
dict2[dict1] = 5
TypeError: unhashable type: ‘dict’

The reason for this error is that mydict1 is unhashable, and therefore cannot be used as a key in mydict2.

Note: We cannot be able to use a dictionary as a key in a dictionary or as an element in a set because dict objects are mutable and unhashable.

How to Fix “TypeError: unhashable type: ‘dict'”?

Now that we already know what causes the “python unhashable type ‘dict’” error message, let’s try some solutions to fix it.

Solution 1: Convert the Dictionary to a Hashable Type

The first solution is to convert the dictionary to a hashable type, such as a tuple.

Since tuples are immutable and hashable, they can be used as keys in a dictionary or as elements in a set.

For example, we can convert mydict1 to a tuple and use it as a key in mydict2:

mydict1 = {'a': 1, 'b': 2}
mydict2 = {'c': 3, 'd': 4}
mydict2[tuple(mydict1.items())] = 5

print(mydict2)

This program code creates two dictionaries, mydict1 and mydict2 , each with some key-value pairs.

Then, it adds a new key-value pair to mydict2. The key is a tuple of the key-value pairs in mydict1, and the value is 5.

Finally, the print statement is used to display the final contents of mydict2 after the new key-value pair has been added.

When you run this code, it will print the contents of mydict2 after the new key-value pair has been added.

The output will be:

{‘c’: 3, ‘d’: 4, ((‘a’, 1), (‘b’, 2)): 5}

Solution 2: Convert the Dictionary to a JSON string

Another way to solve this error is to convert the dictionary to a JSON string before using it as a key.

For example:

import json

my_json = json.dumps({'country': 'Philippines'})

my_dict = {'name': 'Juan', my_json: 'address'}
print(my_dict)

my_key = json.dumps({'country': 'Philippines'})
print(my_dict[my_key])

This code first imports the json module, which provides functions for working with JSON data.

Next, the code creates a JSON string from a dictionary using the json.dumps() function and assigns it to the variable my_json.

Then, a new dictionary my_dict is created with two key-value pairs. The first key is ‘name‘ with a value of ‘Juan‘, and the second key is my_json with a value of ‘address’.

After that, the contents of my_dict are printed to the console.

Finally, the code creates a new variable my_key with the same JSON string value as my_json, and uses it to access the value in my_dict that corresponds to that key.

When you run this code, it will print the contents of my_dict to the console, which should be:

C:\Users\Dell\PycharmProjects\pythonProject\venv\Scripts\python.exe C:\Users\Dell\PycharmProjects\pythonProject\main.py
{‘name’: ‘Juan’, ‘{“country”: “Philippines”}’: ‘address’}
address

Then, it will print the value associated with the my_key, which is ‘address‘.

Solution 3: Use a Different Data Structure

If converting the dictionary to a hashable type isn’t an option, the second solution is using a different data structure that can manage unhashable types, like a list.

For example, we can use a list of dictionaries instead of a dictionary of dictionaries:

# Define a list of dictionaries
list_of_dicts = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}]

# Access the first dictionary in the list and print its value for 'a'
print(list_of_dicts[0]['a'])  # Output: 1

# Access the second dictionary in the list and print its value for 'd'
print(list_of_dicts[1]['d'])  # Output: 4

In this code, we specify a list of dictionaries list_of_dicts, which consist of two dictionaries.

Then, we access the first dictionary in the list using the index [0].

After that, it will print its value for the key ‘a‘ using bracket notation ([‘a’]).

Next, we access the second dictionary in the list using the index [1] and print its value for the key ‘d‘ using bracket notation ([‘d’]).

When you run this code, it will output:

C:\Users\Dell\PycharmProjects\pythonProject\venv\Scripts\python.exe C:\Users\Dell\PycharmProjects\pythonProject\main.py
1
4

This code will display an example on how to use a list of dictionaries to store related data.

Solution 4: Use a Frozenset

The fourth solution is to use a frozenset.

A frozenset is an immutable set, which means it can be used as a key in a dictionary or as an element in a set.

This code shows an example of how to use a frozenset as a key in a dictionary.

For example, we can convert dict1 to a frozenset and use it as a key in dict2:

# Define two dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

# Add a new key-value pair to dict2, where the key is a frozenset of dict1's items and the value is 5
dict2[frozenset(dict1.items())] = 5

# Print the updated dict2
print(dict2)  # Output: {'c': 3, 'd': 4, frozenset({('a', 1), ('b', 2)}): 5}

In this code, we define two dictionaries dict1 and dict2.

Then, we add a new key-value pair to dict2 using bracket notation ([]).

The key is a frozenset of dict1’s items, which means it is an immutable set of (key, value) pairs. The value is simply as 5.

Finally, we print the updated dict2 using the print function.

When you run this code, it will output:

C:\Users\Dell\PycharmProjects\pythonProject\venv\Scripts\python.exe C:\Users\Dell\PycharmProjects\pythonProject\main.py
{‘c’: 3, ‘d’: 4, frozenset({(‘b’, 2), (‘a’, 1)}): 5}

Solution 5: Use one dictionary as a value in another dictionary

A fifth solution is that you cannot use a dictionary as a key in another dictionary, Yet you can use one as a value.

For example:

dict_val = {'id': 1, 'country': 'Philippines'}
my_dict = {'name': 'Juan', 'info': dict_val}

print(my_dict) 
print(my_dict['info'])

In this code, we have a dictionary named dict_val with two key-value pairs: ‘id‘ with a value of 1, and ‘country‘ with a value of ‘Philippines‘.

We also have another dictionary named my_dict with two key-value pairs: ‘name‘ with a value of ‘Juan‘, and ‘info‘ with a value of dict_val.

The first print statement outputs the entire my_dict dictionary, which includes the ‘name‘ and ‘info‘ key-value pairs. The second print statement outputs the value associated with the ‘info‘ key in my_dict, which is the dict_val dictionary.

Output:

C:\Users\Dell\PycharmProjects\pythonProject\venv\Scripts\python.exe C:\Users\Dell\PycharmProjects\pythonProject\main.py
{‘name’: ‘Juan’, ‘info’: {‘id’: 1, ‘country’: ‘Philippines’}}
{‘id’: 1, ‘country’: ‘Philippines’}

Additional Resources

The following are the articles that already been solved in Python typeerror:

Conclusion

In conclusion, the “python typeerror: unhashable type: ‘dict’” error message occurs when you try to use a dictionary as a key in another dictionary or as an element in a set.

To solve this error, you can convert the dictionary to a hashable type, use a different data structure that can handle unhashable types, and use a frozenset.

FAQs

Can I use a dictionary as a value in another dictionary?

Yes, you can use a dictionary as a value in another dictionary. However, you cannot use a dictionary as a key in another dictionary or as an element in a set.

What is a hashable object in Python?

A hashable object in Python is an object that has a hash value that remains the same throughout its lifetime. Examples of hashable objects include integers, floats, and strings.