-2

I have a list as follows:

list1 = [['abc',{2:1,10:8,7:4,3:4,5:6}],['xyz',{3:8,5:7,2:4,1:9}],.......]]

I want to write the list in a o/p file in the below mentioned format where all the dictionary items are sorted in increasing order based on the key values.

'abc' 2:1 3:4 5:6 7:4 10:8

'xyz' 1:9 2:4 3:8 5:7

I have written the code as follows:

for k, v in list1:
    outputfile.write(k + ' ' + ' '.join('{}:{}'.format(key, val) for key, val in v.items()) + '\n')

But I am not able to get the desired result. Please help me with a solution for it.

akira
  • 521
  • 2
  • 5
  • 14

2 Answers2

1

You are looking for sorted():

for k, v in list1:
    print k + ' ' + ' '.join(
        '{}:{}'.format(key, val)
        for key, val in sorted(v.items(), key=lambda x: x[0])
    ) + '\n'

or use itemgetter() instead lambda:

from operator import itemgetter

for k, v in list1:
    print k + ' ' + ' '.join(
        '{}:{}'.format(key, val)
        for key, val in sorted(v.items(), key=itemgetter(0))
    ) + '\n'
xiº
  • 4,605
  • 3
  • 28
  • 39
0

Use sorted function to sort keys

Demo:

list1 = [['abc',{2:1,10:8,7:4,3:4,5:6}],['xyz',{3:8,5:7,2:4,1:9}],]

for i in list1:
    tmp = ""
    for j in sorted(i[1].keys()):
        tmp += " %s:%s"%(j, i[1][j])
    print "'%s'   %s\n"%(i[0], tmp)
Vivek Sable
  • 9,938
  • 3
  • 40
  • 56