失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > python列表写入字典_python – 将列表字典写入CSV文件

python列表写入字典_python – 将列表字典写入CSV文件

时间:2020-09-22 15:42:42

相关推荐

python列表写入字典_python  – 将列表字典写入CSV文件

我正在努力将列表字典写入.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/0923/1815385.html

如果觉得《python列表写入字典_python – 将列表字典写入CSV文件》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。