Skip to content Skip to sidebar Skip to footer

Unhashable Type: 'list' In Dictionary

I wrote some code to somewhat grab new values from a second dictionary and add to a new dictionary. These are the two dictionaries: a = {armani: jeans, dolce: gabbana} b = {jeans:

Solution 1:

It's not something so small. You need to understand some concepts before continuing with your process.

Dictionaries allow you to access their values with keys such as strings or integers rather than indexes (like lists) right ? Well there should be a mechanism behind the curtains to make this happen which is called a hash.

Every time you put a key:value pair inside a dictionary, a hash value is calculated for that key. With immutable objects (Objects that cannot be changed after creation, that can only be re-created), the hash value always the same for the same string or integer or other immutable objects, this is how the dictionary accesses its values with a key.

Mutable objects on the other hand, can't be hashed. Therefore is not fit to be used as a key inside a dictionary. And list is one of them.

If you must, you can convert the list into a tuple to use it in a dictionary as a key.

lst = [1, 2, 3]
tup = tuple(lst)

Keep in mind that you can't change the elements of a tuple after creation, such as;

tup[0] = 1

Which is why it is immutable. You can only replace it with another tuple, if you require its values to be changed.

Note: The tuple cannot contain lists as elements as well, if it is required to be used for hashing (Which would make it mutable).

Post a Comment for "Unhashable Type: 'list' In Dictionary"