Sort the dictionary's items(), and tell sorted to look at the second half of each pair.
scores = {"Ada": 82, "Linus": 95, "Grace": 77, "Hedy": 95}
ranked = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)
print(ranked)[('Linus', 95), ('Hedy', 95), ('Ada', 82), ('Grace', 77)]scores.items() gives (name, score) pairs. key=lambda kv: kv[1] says "sort by the score", and reverse=True puts the highest first. Linus and Hedy tie on 95 and keep their original order: Python's sort is stable.
Getting a dictionary back
Since Python 3.7, a dictionary remembers the order keys went in. Rebuild it from the sorted pairs and it stays sorted:
scores = {"Ada": 82, "Linus": 95, "Grace": 77}
by_score = dict(sorted(scores.items(), key=lambda kv: kv[1]))
print(by_score)
print(list(by_score)[0], "is lowest"){'Grace': 77, 'Ada': 82, 'Linus': 95}
Grace is lowestTies: sort by score, then by name
Return a tuple from the key and Python sorts by the first item, then the second. Negate the number to get "highest score first, then A to Z":
scores = {"Ada": 82, "Linus": 95, "Grace": 77, "Hedy": 95}
for name, score in sorted(scores.items(), key=lambda kv: (-kv[1], kv[0])):
print(f"{score} {name}")95 Hedy 95 Linus 82 Ada 77 Grace
Only want the top few?
For the top 3 of a large dictionary, heapq.nlargest skips sorting everything:
import heapq scores = {"Ada": 82, "Linus": 95, "Grace": 77, "Hedy": 91, "Alan": 60} print(heapq.nlargest(3, scores.items(), key=lambda kv: kv[1]))
[('Linus', 95), ('Hedy', 91), ('Ada', 82)]If the dictionary holds counts, you probably want a Counter instead, which has most_common(n) built in. And sorted with key= works the same way on any list, not just dictionaries.