TypeError: unhashable type: ‘list’
Srinivas Ramakrishna
Posted on October 19, 2021
ItsMyCode |
TypeError: unhashable type: ‘list’ usually occurs when you use the list as a hash argument. In simple terms, if you use a list as a key in the dictionary, you will encounter a TypeError: unhashable type: ‘list’.
TypeError: unhashable type: ‘list’
If you try to add any unhashable object such as a dictionary to the key, you will encounter TypeError: unhashable type: ‘dict’.
If you try to add any unhashable object such as a list to the key, you will encounter TypeError: unhashable type: ‘list’.
Dictionary in Python is an unordered collection to *store data values in key:value pairs. * Key acts as an identifier to access and retrieve the value in the dictionary.
The keys can contain only immutable hashable types such as strings, boolean, integers, tuples are hashable, which means the value doesn’t change during its lifetime. It will allow Python to create unique hash values for the keys.
Example – unhashable type: ‘list’
This error shows that the fruits key [2,4,6
] is a list and not a hashable type in Python. Dictionary keys must be immutable types, and the list is a mutable type.
# Python TypeError: unhashable type: 'list'
fruits = {"Apple": 100, [2, 4, 6]: 'Qty'}
print("The fruits dictionary is ", fruits)
Output
Traceback (most recent call last):
File "c:\Projects\Tryouts\listindexerror.py", line 3, in <module>
fruits = {"Apple": 100, [2, 4, 6]: 'Qty'}
TypeError: unhashable type: 'list'
Solution to TypeError: unhashable type: ‘list’.
There are multiple solutions to resolve the *unhashable type: ‘list’ * error. Let’s take a look at each of these solutions in detail.
Solution 1 – By Converting list into a tuple
The easiest way to resolve this error is to convert the list into a tuple. Though tuples may seem similar to lists, they are often used for different purposes. Tuples are immutable and contain a heterogeneous sequence of elements that are accessed via unpacking or indexing.
On the other hand, lists are mutable, and the elements are homogeneous, and the elements are accessed by iterating over the list.
# Fix TypeError: unhashable type: 'list'
fruits = {"Apple": 100, (2, 4, 6): 'Qty'}
print("The fruits dictionary is ", fruits)
Output
The fruits dictionary is {'Apple': 100, (2, 4, 6): 'Qty'}
Solution 2 – By Adding list as a value in a dictionary
Since we know that lists are mutable, instead of adding lists as a key in the dictionary, you could store it as a value. The example below demonstrates how to add a list into a dictionary as a value.
# Solution 2 TypeError: unhashable type: 'list'
fruits = {"Apple": 100, "Qty":[10,20,30]}
print("The fruits dictionary is ", fruits)
Output
The fruits dictionary is {'Apple': 100, 'Qty': [10, 20, 30]}
The post TypeError: unhashable type: ‘list’ appeared first on ItsMyCode.
Posted on October 19, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.