Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a dictionary by key? [duplicate]

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.

like image 708
Imoum Avatar asked Mar 25 '13 11:03

Imoum


People also ask

Can you sort a dictionary based on keys?

Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.

Can dictionary have duplicate key values?

The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.

How do I sort a list of dictionaries by key?

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.


1 Answers

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')]) 
like image 110
NPE Avatar answered Sep 23 '22 15:09

NPE