我正在尝试将列表字典写入csv文件。解决方案:Write dictionary of lists to a CSV file
会修剪更长的列表。例如,如果我想写以下内容:
d = {"key1": [1, 2, 3], "key2": [4, 5, 6], "key3": [7, 8, 9, 11]}
with open("test.csv", "wb") as outfile:
writer = csv.writer(outfile)
writer.writerow(d.keys())
writer.writerows(zip(*d.values()))
结果是
key3 key2 key1
7 4 1
8 5 2
9 6 3
答案 0 :(得分:2)
快速简单的答案是使用itertools.izip_longest
代替zip
import itertools
import csv
d = {"key1": [1, 2, 3], "key2": [4, 5, 6], "key3": [7, 8, 9, 11]}
with open("test.csv", "wb") as outfile:
writer = csv.writer(outfile)
writer.writerow(d.keys())
writer.writerows(itertools.izip_longest(*d.values()))