Order by limit N
Your task
Implement ORDER BY ... LIMIT N (top-N). Given rows (list of dicts), a sort_col, a direction ('asc' or 'desc'), and an integer n, return the first n rows after sorting by row[sort_col] in the given direction. The sort must be stable, so rows with equal sort keys keep their input order. If n is greater than the row count, return all rows; if n <= 0, return an empty list. Return the list of selected rows.
Examples
top_n(rows: list[dict], sort_col: str, direction: str, n: int) -> list[dict]Example 1
Input
top_n([{"id": 1, "s": 30}, {"id": 2, "s": 10}, {"id": 3, "s": 20}], "s", "desc", 2)Output
| id | s |
|---|---|
| 1 | 30 |
| 3 | 20 |