1

I have a Python dictionary which holds pairs of key/value:

visited = {
'3':['A', '0'], 
'25':['U', '3'],
'1':['G', '0'],
'32':['C', '0'],
'24':['C', '1'],   
'27':['U', '0'],
'17':['C', '5'], 
'15':['G', '1'], 
'4':['G', '2']
}

I tried to sort them with collections

import collections

...

s = collections.OrderedDict(sorted(visited.items()))
for k, v in s.iteritems():
    print ' '.join(v)

And I receive:

1 G 0
15 G 1
17 C 5
24 C 1
25 U 3
3 A 0
32 C 0
4 G 2

How could I repare it:

1 G 0
3 A 0
4 G 2 
15 G 1
17 C 5
24 C 1
25 U 3
32 C 0
eudaimonia
  • 1,406
  • 1
  • 15
  • 28

1 Answers1

4

You are sorting strings and you wanted to sort by numbers:

>>> s = OrderedDict((k, visited[k]) for k in sorted(visited, key=int))
>>> s
OrderedDict([('1', ['G', '0']),
             ('3', ['A', '0']),
             ('4', ['G', '2']),
             ('15', ['G', '1']),
             ('17', ['C', '5']),
             ('24', ['C', '1']),
             ('25', ['U', '3']),
             ('27', ['U', '0']),
             ('32', ['C', '0'])])
wim
  • 338,267
  • 99
  • 616
  • 750