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.

Easy Python 3.9+ Aug 9, 2026 Database scaling & optimization 16 views 0 copies

Python code

28 lines
Python 3.9+
import 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

stdout
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

  1. Use `heapq.nlargest(N, scores, key=lambda x: x['score'])` for better performance on huge datasets
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Database scaling & optimization

Related tutorials and quizzes for this topic.