38

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
  • 34,080
  • 14
  • 96
  • 122
Imoum
  • 715
  • 2
  • 12
  • 23

3 Answers3

11

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
  • 464,258
  • 100
  • 912
  • 987
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.
  • 30,095
  • 43
  • 103
  • 169
3

Python dictionaries are unordered (for definition)

You can use OrderedDict instead

DonCallisto
  • 28,203
  • 8
  • 66
  • 94