. Advertisement .
..3..
. Advertisement .
..4..
The “TypeError: unhashable type: ‘list’” is becoming popular during you are working on Python at the moment. In this article, we will show you how to solve this error in a rapid way. Let’s get started now.
When will “TypeError: unhashable type: ‘list’” occur?
This “TypeError: unhashable type: ‘list’” will appear when you attempt to add lists as the dictionary’s key.
Here is an example that illustrates this error.
Code:
example_dict = {'football player': 'Davies', ['LB', 'LWB', 'LM']: 'position'}
Output:
Traceback (most recent call last):
File "code.py", line 1, in <module>
example_dict = {'football player': 'Davies', ['LB', 'LWB', 'LM']: 'position'}
TypeError: unhashable type: 'list'
The primary cause behind this error was applying the unhashable type inside the dictionary.
How to troubleshoot “Typeerror: unhashable type ‘list’”?
Approach 1: Use ‘Tuple’
All you need to do is to convert the list to a ‘tuple’
example_dict = {'football player': 'Davies', tuple(['LB', 'LWB', 'LM']): 'position'}
print(example_dict)
print(example_dict[tuple(['LB', 'LWB', 'LM'])])
Then, run the code and check the result.
Output:
{'football player': 'Davies', ('LB', 'LWB', 'LM'): 'position'}
position
As you can see, the output above is clear, and the “Typeerror: unhashable type ‘list’” is eliminated successfully.
Approach 2: Convert the list to a JSON string
The next solution is converting the list to a JSON string. Let’s start with the code below.
import json
example_json = json.dumps(['RB', 'RWB', 'CDM'])
exp_dict1 = {'football player': 'Lahm', example_json: 'position'}
print(exp_dict1)
print(exp_dict1[json.dumps(['RB', 'RWB', 'CDM'])])
You should use JSON.dumps method transforms a Python object to the JSON formatted string. It operates since strings are hashable.
Lastly, run the code, and the output is:
{'football player': 'Lahm', '["RB", "RWB", "CDM"]': 'position'}
position
That’s cool. This error disappeared entirely.
Warnings:
– Hashable objects consist of: ‘int,’ ‘bool,’ and ‘tuple.’
– Unhashable objects are: ‘set’, ‘dict’, and ‘list.’
The ‘tuples’ are only hashable if their elements are hashable.
Approach 3: Use the hash() function with unhashable objects
You should have the precise hash value of the object in this case.
exp_dict2 = {'player': 'Reus', hash(tuple(['CM', 'CAM'])): 'position'}
print(exp_dict2)
print(hash(tuple(['CM', 'CAM'])))
Now, run the code, and the output is:
{'player': 'Reus', 8930775466655796838: 'position'}
8930775466655796838
Great! Your problem is fixed successfully.
Conclusion
That’s all about the “Typeerror: unhashable type ‘list’” and even ideal solutions that you need to care about. Comment on this post to let us know what your perspective is. Thanks!
Read more:
→ How To Fix The TypeError: Unhashable Type: ‘Dict’ – A Complete Guide
Leave a comment