# Python : How to sort a dictionary by value

+2 votes
I am using dictionary data structure to store keys and values. How can I sort the dictionary by values?

E.g. aa={'a':343,'b':23,'c':765,'d':78,'e':901} should result into aa={'b':23,'d':78,'a':343,'c':765,'e':901}

## 1 Answer

0 votes
by (33.0k points)
edited by

Well, dictionaries are inherently orderless, so you cannot sort it by values, however, you can get a list representation of a dictionary that is sorted. Have a look at the following example. It shows how to get sorted list representation using both key and value.

>>> import operator
>>> aa={'a':343,'b':23,'c':765,'d':78,'e':901}
>>> sorted_aa = sorted(aa.items(), key=operator.itemgetter(1)) #sort by values
>>> sorted_aa_1 = sorted(aa.items(), key=operator.itemgetter(0)) #sort by keys
>>> sorted_aa
[('b', 23), ('d', 78), ('a', 343), ('c', 765), ('e', 901)]
>>> sorted_aa_1
[('a', 343), ('b', 23), ('c', 765), ('d', 78), ('e', 901)]

Approach 2

Using most_common() function of Counter module.

>>> from collections import Counter
>>> aa={'a':343,'b':23,'c':765,'d':78,'e':901}
>>> Counter(aa).most_common()
[('e', 901), ('c', 765), ('a', 343), ('d', 78), ('b', 23)]
>>> Counter(aa).most_common()[::-1]
[('b', 23), ('d', 78), ('a', 343), ('c', 765), ('e', 901)]

+2 votes
1 answer
+2 votes
1 answer
+2 votes
1 answer
+2 votes
1 answer
+2 votes
1 answer