TypeError unhashable type ‘list’

When you associate list which is an unhashable data type as a key in a dictionary, then Python generates the error TypeError unhashable type ‘list’ Table of Contents Unhashable objects in Python:TypeError unhashable type ‘list’:Example:Solution:Example:Conclusion: …

TypeError unhashable type 'list'

When you associate list which is an unhashable data type as a key in a dictionary, then Python generates the error TypeError unhashable type ‘list’

Unhashable objects in Python:

The immutable objects like integer, Boolean, string etc. are hashable objects because their values will always remain constant. Whereas list, dictionary are unhashable objects because their values can be edit. 

TypeError unhashable type ‘list’:

The dictionary in Python has two part key and value. Every value has a label linked key. If you want to call any value you can directly reference its key. Although the values in dictionary can be of any data type or they can be list or string as well. But the data type of the key must be of some hashable data type. so whenever you assign any value with an unhashable type key then the TypeError unhashable type ‘list’ generates. 

Example:
number ={ 3:'three', [5,9]:'five and nine',20:'twenty'}
print(number)

TypeError unhashable type 'list'

In the example above we want to print a number dictionary for which we assign every value with a key. But we have use the list data type so we get the error TypeError: unhashable type ‘list’.

Solution:

This error can be solve by using tuple. If you want to insert list as key of dictionary, then change the list to tuple. 

Example:
number ={ 3:'three', tuple[5,9]:'five and nine',20:'twenty'}
print(number)

TypeError unhashable type 'list'

Here we use tuple which is a hashable data type to solve this problem.

Conclusion:

When you associate list which is an unhashable data type as a key in a dictionary, then Python generates the error TypeError unhashable type ‘list’. To avoid this error use hashable data types as a key of a value. Or if you want to use list as a key then change list to tuple.

Suggested Read: 500 Internal server error

Leave a Comment