How to sort a dictionary by key
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')])
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)