Python throws typeerror: unhashable type list when an integer or float is expected but got list. Internally, hash values are the integer representation of dictionary keys which are used for fast lookup of values. Since dictionary keys can’t be a list so Python will throw error when it finds one.

Code Example

d = {'a': 'Tony', 3: 'Stark', 'c': ['is'], ['d']: 'Ironman'}
print(d)

Traceback (most recent call last):
  File "jdoodle.py", line 1, in <module>
    d = {'a': 'Tony', 3: 'Stark', 'c': ['is'], ['d']: 'Ironman'}
TypeError: unhashable type: 'list'

The above code is throwing “typeerror: unhashable type list”. Can you figure out why? The first 3 entries 'a', 3 and 'c' are perfectly valid. All these keys are hashable and Python has no issues with them. The values of all the keys are valid too.

The fourth key is problematic. We are passing a list as 4th key. ['d'] can’t be hashed and hence Python faces trouble. If we convert it into a string as 'd' then this will work fine.

Another solution is to convert the list into tuple. Tuples are hashable. So, ['d'] could get valid if we convert it to ('d'). In fact, we can have multiple values in tuple like ('d', 'e', 'f') and it will still work fine.

    Tweet this to help others

Live Demo

Demo might not work in private window (incognito)

Comments

About the Author

akamit

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles