Python:使用有序列将字典写入文本文件

时间:2013-07-31 17:56:21

标签: python text dictionary

我有一个字典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))。谢谢大家!

3 个答案:

答案 0 :(得分:1)

现在,通过使用精彩的Pandas

,这是一种替代,更简单,更有效的方法
import pandas as pd

order=['mix', 'meow']
D = {'foo':{'meow':1.23,'mix':2.34}, 'bar':{'meow':4.56, 'mix':None}, 'baz':{'meow':None,'mix':None}}

df = pd.DataFrame(D).T.reindex(columns=order)

df.to_csv('./foo.txt', sep='\t', na_rep="none")

结果:

$ python test1.py
$ cat foo.txt
        mix     meow
bar     none    4.56
baz     none    none
foo     2.34    1.23

答案 1 :(得分:0)

利用“订单”变量驱动一些发电机:

def dict2txt(D, writefile, column1='-', delim='\t', width=20, order=['mix','meow']):
    import csv
    # simplify formatting for clarity
    fmt = lambda s: '{!s:{}}'.format(s, width)
    with open(writefile, 'w') as f:
        writer = csv.writer(f, delimiter=delim)
        writer.writerow([fmt(column1)] + [fmt(s) for s in order])
        for i in D.keys():
            writer.writerow([fmt(i)] + [fmt(D[i][k]) for k in order])

行仍然是无序的。所以你可能想要这样的东西:“for i in sorted(D.keys()):”

答案 2 :(得分:0)

这是我从你的代码中得到的:

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 order:    
        head.append('{!s:{}}'.format(i,width))

    writer.writerow(head)

    for i in sorted(D.keys()):
      row = ['{!s:{}}'.format(i,width)]
      for k in order: row.append('{!s:{}}'.format(D[i][k],width))
      writer.writerow(row)

文件内容:

-                       mix                     meow                
bar                     None                    4.56                
baz                     None                    None                
foo                     2.34                    1.23