Rankings: Top-N with sorted & max
Lesson 4 of 5 · View course roadmap
Learn the idea
Every dashboard has a leaderboard: best sellers, slowest pages, biggest customers. In Python a ranking is three moves:
items.items()— get (name, number) pairs out of a dictsorted(..., key=lambda pair: pair[1], reverse=True)— order by the number, biggest first[:3]— slice the podium
Need just the single winner? max(data, key=data.get) reads almost like English. And enumerate(top, start=1) numbers your report lines without a manual counter.
Where you'll use this
Top-N queries power every leaderboard, 'best sellers' shelf, alerting system ('5 slowest endpoints') and recommendation panel. It's among the most-run query shapes in industry.
Common mistakes
- Sorting the dict instead of its .items() — you'll rank keys alphabetically and wonder where the numbers went.
- Forgetting reverse=True and shipping a bottom-3 as your top-3.
- Slicing before sorting — [:3] on unsorted items is just the first three, not the best three.
Pro tip
For huge datasets, heapq.nlargest(3, units.items(), key=lambda p: p[1]) finds the podium without fully sorting a million rows.
Try it yourself
The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +35 XP
From units = {"laptop": 12, "mouse": 41, "monitor": 9, "keyboard": 25, "webcam": 17}, print the top 3 sellers as 1. mouse (41 sold), 2. keyboard (25 sold), 3. webcam (17 sold).
1. mouse (41 sold) 2. keyboard (25 sold) 3. webcam (17 sold)
top = sorted(units.items(), key=lambda p: p[1], reverse=True)[:3], then enumerate(top, start=1).
units = {"laptop": 12, "mouse": 41, "monitor": 9, "keyboard": 25, "webcam": 17}
top = sorted(units.items(), key=lambda pair: pair[1], reverse=True)[:3]
for rank, (product, sold) in enumerate(top, start=1):
print(f"{rank}. {product} ({sold} sold)")
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.