将列表字典写入 CSV 文件 [英] Write dictionary of lists to a CSV file

查看:56
本文介绍了将列表字典写入 CSV 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力将列表字典写入 .csv 文件.

I'm struggling with writing a dictionary of lists to a .csv file.

我的字典是这样的:

dict[key1]=[1,2,3]
dict[key2]=[4,5,6]
dict[key3]=[7,8,9]

我希望 .csv 文件看起来像:

I want the .csv file to look like:

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

到目前为止一切顺利……但是,我的问题是我不知道如何将一个列表分配给相应的列.例如:

So far so good... However, my problem is that I don't know how I could assign one list to the corresponding column. e.g.:

for i in range(0,len(dict[key1])):
    writefile.writerow([dict[key1][i],dict[key2][i],dict[key3][i])

将随机填充列.另一个问题是,我必须手动填写键,并且不能将它用于另一个有 4 个键的字典.

will randomly fill the columns. Another problem is, that I have to manually fill in the keys and can't use it for another dictionary with 4 keys.

推荐答案

如果你不关心你的列的顺序(因为字典是无序的),你可以简单地使用 zip():

If you don't care about the order of your columns (since dictionaries are unordered), you can simply use 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

如果您确实关心顺序,则需要对键进行排序:

If you do care about order, you need to sort the keys:

keys = sorted(d.keys())
with open("test.csv", "wb") as outfile:
   writer = csv.writer(outfile, delimiter = "	")
   writer.writerow(keys)
   writer.writerows(zip(*[d[key] for key in keys]))

结果:

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

这篇关于将列表字典写入 CSV 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆