我有一个构建的字典列表,以便每个字典代表特定事件的数据。数据是:
events = [{'date': '7:30 PM ET, October 29, 2014',
'guests': ['Cleopatra', 'Ghandi'],
'location': 'Cairo, Egypt',
'random_nums': [1, 2, 3, 4]},
{'date': '8:00 PM ET, November 1, 2014',
'guests': ['JFK', 'Abe Lincoln'],
'location': 'Dallas, TX',
'random_nums': [5, 6, 7, 8]},
{'date': '8:30 PM ET, November 3, 2014',
'guests': ['Joan of Arc', 'Genghis Khan'],
'location': 'the Moon',
'random_nums': [9, 10, 11, 12]}]
我正在尝试写入CSV,以便每个偶数都表示为自己的行,公共键作为标题。
date random_nums guests location
7:30 PM ET, October 29 1, 2, 3, 4 Cleopatra, Ghandi Cairo, Egypt
8:00 PM ET, November 1 5, 6, 7, 8 JFK, Abe Lincoln Dallas, TX
8:30 PM ET, November 3 9, 10, 11, 12 Joan of Arc, Genghis Khan the Moon
我已经看过很多关于这个主题的类似帖子,但没有解决这个问题。我意识到存在一些分隔符问题,因为字符串中有逗号。
所以,我需要帮助:
这里和我一样接近:
with open("output.csv", "wb") as f:
writer = csv.writer(f, delimiter = ';')
writer.writerow(list(events[1].keys()))
for event in events:
print event.values()
for row in event.values():
writer.writerow(row)
答案 0 :(得分:0)
由于你有一堆词典,使用csv.DictWriter
可能会更简单,它会自动对齐键。像
with open("output.csv", "wb") as f:
writer = csv.DictWriter(f, fieldnames=list(events[0]), delimiter = ';')
writer.writeheader()
for event in events:
outevent = event.copy()
outevent["random_nums"] = ", ".join(map(str, outevent["random_nums"]))
outevent["guests"] = ", ".join(outevent["guests"])
writer.writerow(outevent)
将产生
date;random_nums;guests;location
7:30 PM ET, October 29, 2014;1, 2, 3, 4;Cleopatra, Ghandi;Cairo, Egypt
8:00 PM ET, November 1, 2014;5, 6, 7, 8;JFK, Abe Lincoln;Dallas, TX
8:30 PM ET, November 3, 2014;9, 10, 11, 12;Joan of Arc, Genghis Khan;the Moon
请注意,您可以使用制表符甚至逗号作为分隔符 - 如果分隔符存在于元素中,则会被适当引用。