我正在努力将列表字典写入.csv文件.
这就是我的字典的样子:
dict[key1]=[1,2,3]
dict[key2]=[4,5,6]
dict[key3]=[7,8,9]
我希望.csv文件看起来像:
key1 key2 key3
1 4 7
2 5 8
3 6 9
起初我写了标题:
outputfile = open (file.csv,'wb')
writefile = csv.writer (outputfile)
writefile.writerow(dict.keys())
到目前为止一切都那么好……但是,我的问题是我不知道如何将一个列表分配给相应的列.例如.:
for i in range(0,len(dict[key1])):
writefile.writerow([dict[key1][i],dict[key2][i],dict[key3][i])
将随机填充列.另一个问题是,我必须手动填写密钥,不能将它用于另一个带有4个密钥的字典.
解决方法:
如果你不关心列的顺序(因为字典是无序的),你可以简单地使用zip():
d = {"key1": [1,2,3], "key2": [4,5,6], "key3": [7,8,9]}
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
如果您关心订单,则需要对密钥进行排序:
keys = sorted(d.keys())
with open("test.csv", "wb") as outfile:
writer = csv.writer(outfile, delimiter = "\t")
writer.writerow(keys)
writer.writerows(zip(*[d[key] for key in keys]))
结果:
key1 key2 key3
1 4 7
2 5 8
3 6 9
标签:python,dictionary,csv
来源: https://codeday.me/bug/20190923/1815385.html