How to sort a dictionary by key? [duplicate]

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)