将不同长度列表的字典写入csv文件

时间:2015-06-23 21:43:06

标签: python-2.7

我正在尝试将列表字典写入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
11从key3中删除。有什么想法吗?

1 个答案:

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