0

我有一本字典 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)). 谢谢各位!

4

3 回答 3

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
于 2013-07-31T19:51:03.147 回答
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()):”

于 2013-07-31T18:37:22.517 回答
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                
于 2013-07-31T19:00:57.430 回答