The TypeError: unhashable type:’dict’ error occurs when you use any unhashable/immutable objects like lists, dictionaries, etc as a key in the dictionary.
In this article, let’s understand why this error is seen? Also, look at different ways of fixing it.
Table of Contents
Understanding TypeError: unhashable type ‘dict’
A dictionary is a collection of key-value pairs. It is unordered. Hence, it can’t be indexed using numbers. Instead, it is indexed using keys.
A key in a dictionary must be unique. It must be of an immutable type like a string, a key, or a tuple. It must not be of the mutable/hashable type, like a list, a dictionary, etc.
This is what the Python Offical Site has to about keys :
Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like
append()
andextend()
.
We have a list named players that contains dictionary objects holding the names and ages of the players. We have another empty dictionary selected_players. When we add the players less than 40 years old to the selected_players dictionary, we see the error. Refer to the below example.
players =[ {'name' : "Alice" , 'age':50 }, {'name': "Bob" , 'age':20}, {'name': "Charlie" , 'age': 25} ] selected_players= {} for player in players: if player['name'] == "Alice" : selected_players[player]='selected'
Output :
Traceback (most recent call last): File "C:\Users\paian\PycharmProjects\PythonHowTo\venv\Solutions\TypeError_unhashable_type_dict.py", line 25, in <module> selected_players[player]='selected' TypeError: unhashable type: 'dict'
Explanation :
If you try to add a dictionary (unhashble object) as a key to another dictionary, you will see the error. The keys that you use in the dictionary should be mandatorily hashable.
To fix this error, you can do one of the following:
- Convert the dictionary (the one you are using as a key, i.e., player) to a hashable type like a tuple or set.
- Check if you have mistakenly specified the dictionary instead of referencing its key/value.
Fix 1: Convert the dictionary to a hashable object.
You can convert a dictionary-type object to a tuple or a frozenset (an immutable set) and then use it as a key for the new dictionary.
Convert the dict to tuple
To convert a dictionary with key-value pairs to a tuple, use the following.
tuple(dict.items())
To convert only the keys in a dictionary to a tuple, use the following.
tuple(dict.keys())
To convert only the values in a dictionary to a tuple, use the following.
tuple(dict.values())
In the below example, we convert the dictionary to a tuple. Then, assign it as a key for the selected_players dictionary. Notice all the examples, and then choose the fits in your case.
players =[ {'name' : "Alice" , 'age':50 }, {'name': "Bob" , 'age':20}, {'name': "Charlie" , 'age': 25} ] print("Selected players dictionary after using tuple(dict.items())") selected_players= {} for player in players: if player['age'] < 40 : selected_players[tuple(player.items())]='selected' print(selected_players) print("\n") print("Selected players dictionary after using tuple(dict.keys())") selected_players= {} for player in players: if player['age'] < 40 : selected_players[tuple(player.keys())]='selected' print(selected_players) print("\n") print("Selected players dictionary after using tuple(dict.values())") selected_players= {} for player in players: if player['age'] < 40 : selected_players[tuple(player.values())]='selected' print(selected_players) print("\n")
Output :
Selected players dictionary after using tuple(dict.items()) {(('name', 'Bob'), ('age', 20)): 'selected', (('name', 'Charlie'), ('age', 25)): 'selected'} Selected players dictionary after using tuple(dict.keys()) {('name', 'age'): 'selected'} Selected players dictionary after using tuple(dict.values()) {('Bob', 20): 'selected', ('Charlie', 25): 'selected'}
Convert dict to an immutable set(frozenset)
To convert a dictionary with key-value pairs to a frozen set, use the following.
frozenset(dict.items())
To convert a dictionary with its keys to a frozen set, use the following.
frozenset(dict.keys())
To convert a dictionary with its values to a frozen set, use the following.
frozenset(dict.values())
In the below example, we convert the dictionary to a frozenset. Then, assign it as a key for the selected_players dictionary. Notice all the examples, and then choose the caters to your needs.
players =[ {'name' : "Alice" , 'age':50 }, {'name': "Bob" , 'age':20}, {'name': "Charlie" , 'age': 25} ] print("Selected players dictionary after using tuple(dict.items())") selected_players= {} for player in players: if player['age'] < 40 : selected_players[frozenset(player.items())]='selected' print(selected_players) print("\n") print("Selected players dictionary after using tuple(dict.keys())") selected_players= {} for player in players: if player['age'] < 40 : selected_players[frozenset(player.keys())]='selected' print(selected_players) print("\n") print("Selected players dictionary after using tuple(dict.values())") selected_players= {} for player in players: if player['age'] < 40 : selected_players[frozenset(player.values())]='selected' print(selected_players) print("\n")
Output :
Selected players dictionary after using tuple(dict.items()) {frozenset({('name', 'Bob'), ('age', 20)}): 'selected', frozenset({('age', 25), ('name', 'Charlie')}): 'selected'} Selected players dictionary after using tuple(dict.keys()) {frozenset({'name', 'age'}): 'selected'} Selected players dictionary after using tuple(dict.values()) {frozenset({20, 'Bob'}): 'selected', frozenset({'Charlie', 25}): 'selected'}
Fix 2: Instead of a dictionary, reference the appropriate value.
Were you referencing a specific value in the dictionary? If you are doing so, reference the key or value appropriately.
In the below example, we reference the value instead of the dictionary.
players =[ {'name' : "Alice" , 'age':50 }, {'name': "Bob" , 'age':20}, {'name': "Charlie" , 'age': 25} ] selected_players= {} for player in players: if player['age'] < 40 : selected_players[player['name']]='selected' print(selected_players) print("\n")
Output :
{'Bob': 'selected', 'Charlie': 'selected'}
Conclusion
We have discussed the causes of TypeError: unhasable type:’dict’. We have also seen different options available to fix this error. We hope this article has been informative.
Kindly comment and let us know if this helped you.
Thanks for reading.
1 thought on “[FIX] TypeError: unhasable type:’dict’”