2015-06-23 44 views
3

我想写一个列表的字典到csv文件。解决方案如下:Write dictionary of lists to a CSV file写一个不同长度的列表到一个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(zip(*d.values())) 

结果是

key3 key2 key1 
7  4  1 
8  5 2 
9  6 3 

11从KEY3删除。有任何想法吗?

+0

使用一个循环,而不是writerows +拉链 –

+0

我试过的,但不能得到我想要的东西。 – Omar

回答

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())) 
相关问题