How to sort a dictionary by key?

Question:

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.

Asked By: Imoum

||

Answers:

Python dictionaries are unordered (for definition)

You can use OrderedDict instead

Answered By: DonCallisto
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)

Answered By: Jakub M.

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')])
Answered By: NPE
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.