Estimated reading time: 3 minutes
When programming in python you will come across this error quite often, in this case is quite easily fixed once understood.
The problem usually arises when you try to loop through a dictionary with key-value pairs. If you are unsure what a dictionary looks like see W3 Schools
Lets examine those loops that don’t throw the error.
Using a list, produces the following output with no error:
list = [['a'],['b'],['c'],['d'],['e'],['f']] print(type(list)) for i in list: print(i) <class 'list'> ['a'] ['b'] ['c'] ['d'] ['e'] ['f']
If there is a need for a tuple, then the following outputs with no error:
list = (['a'],['b'],['c'],['d'],['e'],['f']) print(type(list)) for i in list: print(i) <class 'tuple'> ['a'] ['b'] ['c'] ['d'] ['e'] ['f']
Using a dictionary, it gives the error you are looking to resolve, but why?
list = {['a'],['b'],['c'],['d'],['e'],['f']} print(type(list)) for i in list: print(i) list = {['a'],['b'],['c'],['d'],['e'],['f']} TypeError: unhashable type: 'list'
To understand the error it is important to step back and figure out what is going on in each scenario:
(A) Looping through the list, it looks at the values on their own, thus the loop completes with no problem.
(B) As with lists, Tuples are immutable ( cannot be modified), more importantly, they can be looped through with no error.
In this case the lists have single values, the dictionary above has only one value, it expects two, hence the error.
How do we fix this error going forward?
The simplest way is to loop through a list of single items with the iterable code below:
fixlist = [['a'],['b'],['c'],['d'],['e'],['f'],['f'],['c']] # Converts fixlist from a list of lists to a flat list, and removes duplicates with set fixlist = list(set(list(itertools.chain.from_iterable(fixlist)))) print(fixlist) Result : ['d', 'f', 'c', 'b', 'a', 'e']
Now your code is only looking to loop through some single values within your list, compared to dictionary key-value pairs.
Approaching solving this problem through an iteration line by line helped to pinpoint the problem.
Consequently the steps I went through to fix the problem involved:
(A) print(type(variable)) – Use this on passing data to see what the data types are, clarifies if this is the problem.
(B) Consequently once the line of code that was throwing the error was found, removing the dictionary fixed the problem.
Or
If a dictionary is required to be looped through, it needs the proper key, value pairs setup.
Conclusion
In conclusion, in order to remove this error it is important to identify the line and or lines, that have a dictionary and covert them to a list
or
if a dictionary is needed ensure that the lists are converted to a dictionary with key, value pairs.
If you would like to see a very good video explanation of this error head over to Brandon Jacobson’s YouTube channel , and make sure to subscribe.
His explantion is below: