Python 3 sort a dict by its values

user2094432 picture user2094432 · Jan 6, 2014 · Viewed 128.5k times · Source

The only methods I found work for python2 or return only list of tuples.

Is it possible to sort dictionary, e.g. {"aa": 3, "bb": 4, "cc": 2, "dd": 1}, by its values?

Order of sorted dictionary I want to achieve is from largest to smallest. I want results to look like this:

bb 4
aa 3
cc 2
dd 1

And after sorting I want to store it into a text file.

Answer

SzieberthAdam picture SzieberthAdam · Jan 6, 2014

itemgetter (see other answers) is (as I know) more efficient for large dictionaries but for the common case, I believe that d.get wins. And it does not require an extra import.

>>> d = {"aa": 3, "bb": 4, "cc": 2, "dd": 1}
>>> for k in sorted(d, key=d.get, reverse=True):
...     k, d[k]
...
('bb', 4)
('aa', 3)
('cc', 2)
('dd', 1)

Note that alternatively you can set d.__getitem__ as key function which may provide a small performance boost over d.get.