我只测试列表中的日期,而不是列表中的位置,日期和标题。有人可以帮我解决这个问题吗?最终结果应该是这样的。
{filename: [location, date, caption]}
这是文件。
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_image_dict(open_csv_file):
'''(file) -> dict of {str: list of str}
The open csv file has the format:
filename,location,date,caption,keywords,keywords, ...
Return a dictionary with key filename and values [location, date, caption]
'''
d = {}
for line in open_csv_file:
info = line.split(',')
filename = info[0]
location = info[1]
date = info[2]
caption = info[3]
if location not in d:
d[filename] = {location:{date: caption}}
return d
答案 0 :(得分:1)
专业提示1:
调试print语句以查看正在处理的内容,即print(info)
问题很可能是因为拆分会留下一个包含单个条目的列表。
arr = "this string will not split to more than one element".split(",")
arr
现在的长度为1,因此会为arr[1]
修改强>
再次查看你的程序,你似乎正在检查插入dict d
的错误内容。您应该检查if filename in d
而不是if location in d
。