Python: Write dictionary to text file with ordered columns -


i have dictionary d where:

d = {'foo':{'meow':1.23,'mix':2.34}, 'bar':{'meow':4.56, 'mix':none}, 'baz':{'meow':none,'mix':none}} 

i wrote code write text file:

def dict2txt(d, writefile, column1='-', delim='\t', width=20, order=['mix','meow']):   import csv   open( writefile, 'w' ) f:     writer, w = csv.writer(f, delimiter=delim), []     head = ['{!s:{}}'.format(column1,width)]     in d[d.keys()[0]].keys(): head.append('{!s:{}}'.format(i,width))     writer.writerow(head)     in d.keys():       row = ['{!s:{}}'.format(i,width)]       k in order: row.append('{!s:{}}'.format(d[i][k],width))       writer.writerow(row) 

but output ignores order = ['mix','meow'] , writes file like:

-       meow    mix     bar     none    4.56    foo     2.34    1.23456 baz     none    none 

how write:

-       mix     meow     bar     4.56    none    foo     1.23456 2.34 baz     none    none 

thanks!

update: @sukritkalra in comments below pointing out code works fine. wasn't reordering column headers!

the line for in d[d.keys()[0]].keys(): head.append('{!s:{}}'.format(i,width)) should read for in order: head.append('{!s:{}}'.format(i,width)). folks!

now, alternate, easier , more efficient way of doing this, using wonderful pandas library

import pandas 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") 

result:

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

Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

php - joomla get content in onBeforeCompileHead function -