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.
Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.
The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.
To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function.
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')])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With