我不知道
为什么在尝试测试此功能时会出现此错误。任何人都可以帮我解决这个问题吗?
d[关键字] = [文件名,关键字]内置。类型错误:不可哈希类型:"列表">
我希望我的最终结果看起来像这样。{'关键字": ['文件名1', '文件名2'...]}其中文件名是在其关键字列表中具有关键字的文件名
这是文件:
images/skating.jpg,East York Arena,2014.11.03,Shea skating.,skating,Shea,boy
images/sunglasses.jpg,High Park,2013.02.03,Cool guy.,Shea,sunglasses,happy
images/skating2.jpg,East York Arena,2014.11.03,Shea skating
again!,skating,Shea
def create_keyword_dict(open_file):
'''(file) -> dict of {str: list of str}
Given an open csv file with the format:
filename,location,date,caption,keywords,keywords, ...
return a new dictionary where the key is a keyword and each value
is a list of filenames that have that keyword in their list of keywords.
'''
d = {}
for line in open_file:
new_d = line.split(',')
filename = new_d[0]
keywords = new_d[5:]
if filename not in d:
d[keywords] = [filename, keywords]
return d
不能将列表用作字典键。用作键的类型需要可哈希处理(这是TypeError: unhashable type
所指的。
而不是使用列表,您需要按单个关键字对文件进行排序和分组,并将它们用作键 - 这具有能够按单个关键字搜索列表的额外好处,而不是要求您拥有文件的所有关键字才能找到它。这样的东西会起作用:
for line in open_file:
new_d = line.split(',')
filename = new_d[0]
keywords = new_d[5:]
for keyword in keywords:
if keyword not in d:
d[keyword] = [filename]
else:
d[keyword].append(filename)