40

i tried to sort dict by key but no chance. this is my dict :

result={'1':'value1','2':'value2',...}

i'm using Python2.7 and i found this

keys = result.keys()
keys.sort()

but this is not what i expected, i have an unsorted dict.

codeforester
  • 39,467
  • 16
  • 112
  • 140
Imoum
  • 745
  • 3
  • 12
  • 24

3 Answers3

12

Standard Python dictionaries are inherently unordered. However, you could use collections.OrderedDict. It preserves the insertion order, so all you have to do is add the key/value pairs in the desired order:

In [4]: collections.OrderedDict(sorted(result.items()))
Out[4]: OrderedDict([('1', 'value1'), ('2', 'value2')])
NPE
  • 486,780
  • 108
  • 951
  • 1,012
9
sorted(result.iteritems(), key=lambda key_value: key_value[0])

This will output sorted results, but the dictionary will remain unsorted. If you want to maintain ordering of a dictionary, use OrderedDict

Actually, if you sort by key you could skip the key=... part, because then the iterated items are sorted first by key and later by value (what NPE uses in his answer)

Jakub M.
  • 32,471
  • 48
  • 110
  • 179
3

Python dictionaries are unordered (for definition)

You can use OrderedDict instead

DonCallisto
  • 29,419
  • 9
  • 72
  • 100