Reputation: 179
I have already checked some question-answers related to Unhashable type : 'list' in stackoverflow, but none of them helped me. Here is my partial code:
keyvalue = {};
input_list_new = input_list;
for file in os.listdir('Directory/'):
pathname = os.path.join('Directory/', file)
dict_table = []; # creates blank 2d array
with open(pathname) as dict_file:
for line in dict_file:
dict_table.append(line.strip().split("\t"))
dict_list = [];
for i in list(range(0, len(dict_table))):
dict_list.append(dict_table[i][0])
matched = list(set(dict_list) & set(input_list))
for i in list(range(0, len(matched))):
temp = [dict_table[0][0]] + dict_table[(dict_list.index(matched[i]))]
input_list_new.insert((input_list_new.index(matched[i])), temp)
dict = {matched[i] : temp}
keyvalue.update(dict)
where dict_table
is a list of lists, dict_list
is just a list & keyvalue
is a python dictionary. The entire code runs well when ever I comment the line input_list_new.insert((input_list_new.index(matched[i])), temp)
, but without that line being commented, it shows Unhashable type : 'list'
error.
Upvotes: 0
Views: 1774
Reputation: 403
Here's my guess .... You mentioned that the error is with the line matched = list(set(dict_list) & set(input_list))
.. That is probably because in either input_list
or dict_list
, you have a list within a list .... the items in a set need to hashable, and hence immutable .. for example you cannot do set([1,5,6,[1,3]])
... that will give the unhashable type list error ... but you can do set([1,5,6,(1,3)])
because a tuple is immutable and hashable
Upvotes: 1
Reputation: 59681
The error message does not correspond to the line
input_list_new.insert((input_list_new.index(matched[i])), temp)
being commented out. If anything, the culprit is the line
dict = {matched[i] : temp}
The problem should be that you are trying to use a list as your dictionary key. Here is the problem in a simple reproducible way:
{[]: 5} # throws TypeError: unhashable type: 'list'
The reason it fails, is because a dictionary is also be called a hashmap (in other languages). The key must be hashable, and in Python trying to use a list as the key throws your error becauses lists are not hashable (see "hashable" entry here).
Avoid using a list as your dictionary key will fix the problem.
Upvotes: 1