You can use the built-in method itemgetter() of operator module to sort a dictionary by key or value in Python as shown in the below example –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import operator import collections dict = {"a": 5,"b": 4,"c": 3,"d": 2,"e": 1} ## Sort by value sklist = sorted(dict.items(), key=operator.itemgetter(1)) print(sklist) ## Returns [('e', 1), ('d', 2), ('c', 3), ('b', 4), ('a', 5)] ## Sort by key svlist = sorted(dict.items(), key=operator.itemgetter(0)) print(svlist) ## Returns [('a', 5), ('b', 4), ('c', 3), ('d', 2), ('e', 1)] ## Return as dictonary skdict = collections.OrderedDict(sklist) svdict = collections.OrderedDict(svlist) print(skdict) print(svdict) |