我有这样的东西:
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/