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.
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.
这是我的猜测...。您提到错误与matched = list(set(dict_list) & set(input_list))
的行matched = list(set(dict_list) & set(input_list))
..可能是因为在input_list
或dict_list
,列表中都有一个列表。 ...集合中的项目需要可哈希化,因此是不可变的。例如,您不能执行set([1,5,6,[1,3]])
...这会导致无法哈希的类型列表错误。 ..但您可以执行set([1,5,6,(1,3)])
因为元组是不可变且可哈希的
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.