Python program: Sort a dictionary by value
List the items of a dictionary from highest to lowest value.
The code
sales = {"tea": 120, "coffee": 340, "juice": 85, "cake": 210} for item, n in sorted(sales.items(), key=lambda kv: kv[1], reverse=True): print(f"{item:<7}{n:>5}") top = dict(sorted(sales.items(), key=lambda kv: kv[1], reverse=True)[:2]) print(top)
Output
coffee 340
cake 210
tea 120
juice 85
{'coffee': 340, 'cake': 210}
How it works
items() gives (key, value) pairs; key=lambda kv: kv[1] sorts them by value. Wrapping in dict() makes a new dictionary in that order.
Python features used
Learn the ideas behind it in the free lesson Dictionaries & Sets.