0

I apologized as I am very new to python. I am iterating through out several name and they all getting the same dictionary key and value. How can i just print the key once and keep appending the value as per iteration to a csv?

     for name in namelist:
       print >> out,','.join(data.keys())
       print >> out,','.join(data.values())
     fundamental_out.close()

the output looks like this

   >>'key1,key2,key3'
   >>'value1,value2,value3'
   >>'key1,key2,key3'
   >>'value1,value2,value3'

say key3 is the Name, key1 and 2 are numeric

how can i get an output like

   >>'key1,key2,key3'
   >>'value1,value2,value3'
   >>'value1,value2,value3'

also is there a way to sort data dictionary in an order so that key3 (i.e. name will be the first column) ?

   >>'key3,key1,key2'
   >>'value3,value1,value2'
   >>'value3,value1,value2'

THANKS!

user2975269
  • 13
  • 1
  • 3

2 Answers2

0

You can use natural sort to sort the dictionary keys:

import re

def natural_sort(l): 
    #https://stackoverflow.com/a/4836734/846892
    convert = lambda text: int(text) if text.isdigit() else text.lower() 
    alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] 
    return sorted(l, key = alphanum_key)

sorted_keys = ['key3'] + natural_sort(data.viewkeys() - {'key3'})

print >> out, ','.join(keys)
for name in namelist:
       print >> out, ','.join(str(data[k]) for k in keys)
Community
  • 1
  • 1
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0
from itertools import chain
def arrange(l):
    return list(chain([l[-1]], l[:-1]))

print ','.join(arrange(map(lambda x: str(x), namelist.keys())))
print ','.join(arrange(map(lambda x: str(x), namelist.values())))
Guy Gavriely
  • 11,228
  • 6
  • 27
  • 42
  • thanks! but how can you print out the first row with the key and second row forward with values iterate through out a list of names and make sure the value is corresponding to the name with corresponding 'key variables'? – user2975269 Nov 11 '13 at 18:10
  • thanks a lot for this! It helps on the sorting. But still printing out the key in each iteration. Is there a way to just print the keys one time and the values keep printing the values with each iteration? – user2975269 Nov 12 '13 at 04:21