python - 将包含数组值的 Python 字典转储到 CSV

标签 python

我有这样的东西:

dict = {}
dict["p1"] = [.1,.2,.3,.4]
dict["p2"] = [.4,.3,.2,.1]
dict["p3"] = [.5,.6,.7,.8] 

如何将字典转储到这种结构的 csv 中? :

.1 .4 .5
.2 .3 .6
.3 .2 .7
.4 .1 .8

非常感谢!

最佳答案

dict 没有顺序,因此您需要 OrderedDict并转置值:

import csv
from collections import OrderedDict
d = OrderedDict()
d["p1"] = [.1,.2,.3,.4]
d["p2"] = [.4,.3,.2,.1]
d["p3"] = [.5,.6,.7,.8]

with open("out.csv","w") as f:
    wr = csv.writer(f)
    wr.writerow(list(d))
    wr.writerows(zip(*d.values()))

输出:

p1,p2,p3
0.1,0.4,0.5
0.2,0.3,0.6
0.3,0.2,0.7
0.4,0.1,0.8

最好避免隐藏内置函数名称,如 dict .

关于python - 将包含数组值的 Python 字典转储到 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30819738/

相关文章:

python - 通过 paramiko 执行长时间运行的命令

python - 如何通过分解两个非常相似的类来为 Argparse 传递类中的参数

python - 类似 cron 的循环任务调度程序设计

python - 如何在 matplotlib 中按不同组绘制直方图?

python - 同时使用 2 个 GPU 进行不同的 TensorFlow\Python

python - 通过Python进行密码子比对?

python - 用列表列表中的第一个元素制作字典

python - 去除 Python 字符串中某些 html 标签的最快方法是什么?

python - 基于另一列的字符串搜索,使用 Spark Dataframe 中的函数创建新列

python - 删除字典中的键/值对不起作用