How to Limit a Result Set to Top N Rows in Python
Sort a list of dictionaries by a numeric key and return only the top N results, formatted as a readable ranked list.
Python code
28 linesimport random
def top_n_mock(limit: int = 5):
"""Return a formatted top-N result set as a mock example."""
# Simulated data source
scores = [
{"name": "Alice", "score": 87},
{"name": "Bob", "score": 92},
{"name": "Charlie", "score": 78},
{"name": "Diana", "score": 95},
{"name": "Eve", "score": 70},
{"name": "Frank", "score": 88},
{"name": "Grace", "score": 91},
]
# Sort by score descending and take top N
top_n = sorted(scores, key=lambda item: item["score"], reverse=True)[:limit]
# Format output
result_lines = [f"Top {limit} performers:"]
for rank, entry in enumerate(top_n, start=1):
result_lines.append(f"{rank}. {entry['name']} — {entry['score']}")
return "\n".join(result_lines)
if __name__ == "__main__":
print(top_n_mock(3))
Output
Top 3 performers:
1. Diana — 95
2. Bob — 92
3. Grace — 91
How it works
The sorted() function with reverse=True sorts the list in descending order by the score key. Slicing with [:limit] keeps only the first N items, mimicking SQL's LIMIT clause behavior. The enumerate(start=1) call assigns human-friendly ranks. This pattern is a safe, pure-Python way to build a top-N view without mutating the original data.
Common mistakes
- Forgetting `reverse=True` and getting the bottom N instead of the top N
- Mutating the original list with `.sort()` instead of using `sorted()` when you need the original order later
- Not handling a `limit` larger than the dataset, which simply returns all rows
Variations
- Use `heapq.nlargest(N, scores, key=lambda x: x['score'])` for better performance on huge datasets
- Use `operator.itemgetter('score')` instead of a lambda for slightly faster key extraction
Real-world use cases
- Fetching the top N highest-scoring users in a leaderboard endpoint without a full table scan.
- Selecting the most recent N log entries from a large in-memory cache for quick debugging.
- Returning the best N recommendations from a scoring model before sending them to an API response.
Sponsored
More from Database scaling & optimization
- Approximate Count with HyperLogLog in Python medium
- B-Tree Insert and In-Order Traversal in Python hard
- Broadcast a Small Reference Table in Python easy
- Build a Full Text Search Index in Python medium
- Build a Partial Index Mock in Python for Database Filtering easy
- Composite index leftmost prefix in Python medium
Keep learning
Related tutorials and quizzes for this topic.