. Advertisement .
..3..
. Advertisement .
..4..
The TypeError: unhashable type: ‘dict’ is a common issue for many Python programmers. But no worry; we have got your back! Let’s see why it occurs in the first place and how we should tackle it.
Why Does It Occur?
A dictionary comprises two parts: values and keys. Keys serve as identifiers that bound themselves to the value. Upon a key reference, you may retrieve the key-associated values.
No objects can function as dictionary keys except for hashable objects. Most immutable objects (such as tuples, frozen sets, integers, and strings) are considered hashable – with only a few unremarkable exceptions. Hence, we cannot use dictionaries as the key in one dictionary.
So how can we add items to the dictionary? The needed step is to specify valid hashable keys. Let’s say “name” can be the valid key, while {“name”: “test”} cannot.
Suppose we want to establish a program to add every bakery cake sold at least five times from one particular dictionary to another.
We will start the process by issuing a list of cakes, and each of these cakes has its own unique dictionary. Then, we will give a transparent definition to the dictionary in which cakes sold five times are stored.
Example (Code):
cakes = [
{
"name": "Black Forest Gateau", "sold": 3
},
{
"name": "Carrot Cake", "sold": 7
},
{
"name": "Coconut and Lime Cake", "sold": 9
}
]
sold_more_than_five = {}
Next, we compile a “for loop”, making it go through the list of the cakes and spot those sold at least five times. Then we will add all these cakes to a dictionary called “sold_more_than_five”
Example (Code) (cont):
for c in cakes:
if c["sold"] > 5:
sold_more_than_five[c] = c["sold"]
print(c["name"] + " has been sold more than five times.")
print(sold_more_than_five)
In the “for loop”, we start comparing whether each dictionary’s “sold” value produces greater values than 5.
The program will add that item to the “sold_more_than_five” dictionary if the answer is yes. Once done, the console will yield a printed message to inform us that this specific cake has been bought at least six times.
Now let’s operate that loop and print the dictionary to our console. Make sure the program works by running those codes:
Example (Error):
Traceback (most recent call last):
File "main.py", line 16, in <module>
sold_more_than_five[c] = c["sold"]
TypeError: unhashable type: 'dict'
Oops! We have run into the error. The code refuses to function because we have wrongly tried to establish one dictionary key via another dictionary.
How To Fix The TypeError: Unhashable Type: ‘Dict’?
The “c” value equates to one dictionary from the cake list, meaning once we attempt to insert an object to the dictionary”sold_more_than_five”, it will accidentally add another dictionary as the key:
sold_more_than_five[c] = c["sold"]
Once we let the “if” statement operate on “Carrot Cake”, the codes will try to run:
Example (Error) (cont):
sold_more_than_five[{"name": "Carrot Cake", "sold": 7}] = 7
That command is invalid since it attempts to add a key dictionary in another dictionary. So how can we solve this problem? One method is to employ the c[“names”] as the dictionary key’s name:
Example (Solution):
sold_more_than_five[c["name"]] = c["sold"]
We are very close! Now run the codes using this revised command.
Example (Output):
Carrot Cake has been sold more than five times.
Coconut and Lime Cake has been sold more than five times.
{'Carrot Cake': 7, 'Coconut and Lime Cake': 9}
Success!
Conclusion
This article has lent clear examples of fixing the TypeError: unhashable type: ‘dict’. ITtutoria always provides the best tutorials for similar Python TypeErrrors (such as “bytes-like object is required, not ‘str'”), so feel free to browse for more support!
Leave a comment