+2 votes
in Programming Languages by (7k points)
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 (13.5k points)

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

...