Python: sorting dict by value

Probably one of the most often task while working with dictionaries in Python is sorting by value. That is how it can be done:

>>> d = {'Canada': 513, 'Sao Tome and Principe': 3, 'Fiji': 1, 'Montenegro': 12, 'Lithuania': 47}
>>> sorted_list = sorted(d, key=d.get, reverse=True)
>>> for i in sorted_list:
...     print i,  d[i]
...
Canada 513
Lithuania 47
Montenegro 12
Sao Tome and Principe 3
Fiji 1
>>>

Didn’t find the answer to your question? Ask it our administrators to reply we will publish on website.

Leave a Reply

Your email address will not be published. Required fields are marked *