Dictionaries in Python preserve insertion order, but that's rarely the order you actually want to display data in — usually you want it ranked by value: the highest score first, the cheapest item first, the most frequent word first. Python's built-in sorted() function can do this directly, without needing a separate sorting algorithm.
The trick is telling sorted() to look at each item's value rather than its key, using the key parameter with a small lambda function.
Sort a Dictionary by Value (Ascending)
scores = {"Alice": 88, "Bob": 95, "Charlie": 72, "Dana": 95}
# sorted() returns a list of (key, value) tuples
sorted_items = sorted(scores.items(), key=lambda item: item[1])
sorted_dict = dict(sorted_items)
print(sorted_dict)
Output:
{'Charlie': 72, 'Alice': 88, 'Bob': 95, 'Dana': 95}
Sort a Dictionary by Value (Descending)
Add reverse=True to flip the order — handy for leaderboards, where you want the highest score first:
scores = {"Alice": 88, "Bob": 95, "Charlie": 72, "Dana": 95}
ranked = dict(sorted(scores.items(), key=lambda item: item[1], reverse=True))
print(ranked)
Output:
{'Bob': 95, 'Dana': 95, 'Alice': 88, 'Charlie': 72}
scores.items() gives you a sequence of (key, value) tuples, and item[1] inside the lambda picks out just the value from each tuple to sort by — item[0] would sort by key instead. Note that Bob and Dana both have a score of 95; Python's sort is stable, meaning items that compare equal keep their original relative order, which is why Bob (who appeared first in the original dictionary) still comes before Dana.
It's also worth remembering that sorted() always returns a new list — the original dictionary is never modified. Wrapping the result in dict(...) turns that sorted list of tuples back into a dictionary that remembers the new order, since regular Python dicts (3.7+) do preserve the order their keys were inserted in.
