Search This Blog

Monday 4 March 2013

Dictionary Sort by Key in Python

You can easily  sort your dictionary by using collections class in python
Either your key is string or integer, you can sort it.


E.g : Sort Dictionary by key (key in string format)

import collections

dict_data = {'a': 'Anil', 'p': 'pinal', 'c': 'chintan', 'z': 'zinal', 'b': 'Bonil','A':'Atul','h':'Haridk','d':'Dhanvit'}

sorted_dict = collections.OrderedDict(sorted(dict_data.items()))

print "Sorted Dict :::",sorted_dict

O/p : Sorted Dict::: OrderedDict([('A', 'Atul'), ('a', 'Anil'), ('b', 'Bonil'), ('c', 'chintan'), ('d', 'Dhanvit'), ('h', 'Haridk'), ('p', 'pinal'), ('z', 'zinal')])

Returns list of tuples

Same way you can sort your dictionary having integer key.

 dict_data = {2:3, 1:89, 4:5, 3:0}
 
 sorted_dict = collections.OrderedDict(sorted(dict_data.items()))
 
 print "Sorted Dict :::",sorted_dict