使用文件名和键从文件创建字典

时间:2017-11-07 01:19:05

标签: python python-3.x

我只测试列表中的日期,而不是列表中的位置,日期和标题。有人可以帮我解决这个问题吗?最终结果应该是这样的。

{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

1 个答案:

答案 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