我知道之前我曾问过这个问题,但是我仍然不确定为什么我现在只在列表中获取日期,而不是在我测试时列表中的位置,日期和标题。有人可以帮我解决这个问题吗?最终结果应该是这样的。
{filename: [location, date, caption]}
我得到了这个
{'images/skating.jpg': {'East York Arena': ['2014.11.03']},
'images/sunglasses.jpg': {'High Park': ['2013.02.03']},
'images/skating2.jpg': {'East York Arena': ['2014.11.03']}}
这是文件。
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 :(得分:2)
这正是你告诉Python在这里做的事情:
d[filename] = {location:{date: caption}}
所以替换它:
d[filename] = [location,date,caption]
答案 1 :(得分:0)
Scharette的回答恰当地指出了这里的核心错误,{filename:
{location: {date: caption}}}
是一个词典的词典,而不是你要求的列表词典({filename: [location, date, caption]}
),但我想简要评论一般的代码。
首先,您在文件中使用逗号分隔格式,因此请使用专为处理这些文件而设计的stdlib模块 - csv
。
import csv
with open("filename.csv") as f:
reader = csv.reader(f)
Reader对象是可迭代的迭代,表示行 - >领域。这样可以很容易地做到:
# from above
for line in reader:
fname, location, date, caption = line[:4]
此处[:4]
切片不会抓取line
的前四个字符,它会在前四个以逗号分隔的字段上运行,因此您的最后一个采样行变为
fname = 'images/skating2.jpg'
location = 'East York Arena'
date = '2014.11.03'
caption = 'Shea skating again!'
你也可以将这一切全部包含在词典理解中。
with open("filename.csv") as f:
reader = csv.reader(f)
result = {fname: (location, date, caption) for line in reader
for fname, location, date, caption in line[:4]}