当我尝试测试此功能时,我不知道为什么会出现此错误。有人可以帮我解决这个问题吗?
d [keywords] = [文件名,关键字] builtins.TypeError:不可用类型:' list'
我希望我的最终结果看起来像这样。 {' keyword":[' filename1',' filename2' ...]} 其中文件名是在关键字列表中包含关键字的文件名
这是文件:
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
答案 0 :(得分:1)
您无法将列表用作字典键。您用作键的类型需要是可清除的(这是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)