Back to Practice
#0112
Top N Records by Key
EasyPython15 min10 XP
Problem
Given a list of dictionaries, key, and n, return the top n records sorted by key descending. Do not mutate the input list.
Why This Matters
Top-N queries show up everywhere: leaderboards, recommendations, highest revenue products, and model error analysis.
Function Signature
def top_n(records, key, n):
Examples
Example 1
Input[{"name":"A","score":5},{"name":"B","score":9}], "score", 1
Output[{"name":"B","score":9}]
The highest score record comes first.
Constraints
- Return the requested value exactly.
- Handle the stated edge cases.
- Keep the solution readable.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 3 hidden categories
Core example
Input[{"name":"A","score":5},{"name":"B","score":9}], "score", 1
Expected[{"name":"B","score":9}]
The highest score record comes first.
Hidden Test Categories
n larger than recordsn equals zeroties keep sorted stability