我有一本字典 D,其中:
D = {'foo':{'meow':1.23,'mix':2.34}, 'bar':{'meow':4.56, 'mix':None}, 'baz':{'meow':None,'mix':None}}
我编写了这段代码以将其写入文本文件:
def dict2txt(D, writefile, column1='-', delim='\t', width=20, order=['mix','meow']):
import csv
with open( writefile, 'w' ) as f:
writer, w = csv.writer(f, delimiter=delim), []
head = ['{!s:{}}'.format(column1,width)]
for i in D[D.keys()[0]].keys(): head.append('{!s:{}}'.format(i,width))
writer.writerow(head)
for i in D.keys():
row = ['{!s:{}}'.format(i,width)]
for k in order: row.append('{!s:{}}'.format(D[i][k],width))
writer.writerow(row)
但输出忽略order = ['mix','meow']
并写入文件,如:
- meow mix
bar None 4.56
foo 2.34 1.23456
baz None None
我如何让它写:
- mix meow
bar 4.56 None
foo 1.23456 2.34
baz None None
谢谢!
更新:感谢@SukritKalra 在下面的评论中指出代码运行良好。我只是没有重新排序列标题!
该行for i in D[D.keys()[0]].keys(): head.append('{!s:{}}'.format(i,width))
应为for i in order: head.append('{!s:{}}'.format(i,width))
. 谢谢各位!