PythonMastery

Sort a dictionary by value in Python

Sort a dictionary by its values, smallest first or largest first, using sorted() with a key function. Also how to sort by key.

A dictionary has no sort() method. Instead, you sort its (key, value) pairs with sorted() and build a new dictionary from the result.

The program

python
stock = {"banana": 12, "apple": 30, "cherry": 5, "mango": 18}

by_value = dict(sorted(stock.items(), key=lambda item: item[1]))
print(by_value)

largest_first = dict(sorted(stock.items(), key=lambda item: item[1], reverse=True))
print(largest_first)
output
{'cherry': 5, 'banana': 12, 'mango': 18, 'apple': 30}
{'apple': 30, 'mango': 18, 'banana': 12, 'cherry': 5}

How it works

Sort by key, or keep only the top few

python
stock = {"banana": 12, "apple": 30, "cherry": 5, "mango": 18}

print(dict(sorted(stock.items())))

top_two = sorted(stock.items(), key=lambda item: item[1], reverse=True)[:2]
for fruit, count in top_two:
    print(fruit, count)
output
{'apple': 30, 'banana': 12, 'cherry': 5, 'mango': 18}
apple 30
mango 18

Without a key, pairs are compared by their first part, so sorted(stock.items()) sorts by key in alphabetical order.

Learn the idea: Dictionaries, Lambda & Functional Programming

A longer explanation: How do I sort a dictionary by value in Python?