Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Rankings: Top-N with sorted & max

13 min 35 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 4 of 5 · View course roadmap
Step 1

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 dict
  • sorted(..., 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.

Step 2

Try it yourself

Blank · autosaved

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”.

PYexample.py
+ Enter to run
Output appears here…
Step 3

Pass the challenge +35 XP

Blank · autosaved

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).

Target output
1. mouse (41 sold)
2. keyboard (25 sold)
3. webcam (17 sold)
PYchallenge.py
Run your code to check it…
Step 4

Check your understanding

1. What does max(units, key=units.get) return?
2. What does enumerate(top, start=1) add to the loop?
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path