How to sort a dictionary by key?

dictionary, python, sorting

Solution

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')])

Problem

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.

Original source

Related problems