Sort Python list by query param order_by

Sort a list of dataclass objects dynamically by a field name passed as a query param, with asc/desc direction support.

Easy Python 3.9+ Aug 9, 2026 API design & gRPC 11 views 0 copies

Python code

28 lines
Python 3.9+
from dataclasses import dataclass


@dataclass
class Item:
    name: str
    price: int


def sort_items(items, order_by, direction="asc"):
    if order_by not in ("name", "price"):
        raise ValueError(f"Unsupported sort field: {order_by}")

    reverse = direction.lower() == "desc"
    return sorted(items, key=lambda item: getattr(item, order_by), reverse=reverse)


if __name__ == "__main__":
    inventory = [
        Item("banana", 3),
        Item("apple", 5),
        Item("cherry", 2),
    ]

    print("Asc by name:", [item.name for item in sort_items(inventory, "name")])
    print("Desc by name:", [item.name for item in sort_items(inventory, "name", "desc")])
    print("Asc by price:", [item.name for item in sort_items(inventory, "price")])
    print("Desc by price:", [item.name for item in sort_items(inventory, "price", "desc")])

Output

stdout
Asc by name: ['apple', 'banana', 'cherry']
Desc by name: ['cherry', 'banana', 'apple']
Asc by price: ['cherry', 'banana', 'apple']
Desc by price: ['apple', 'banana', 'cherry']

How it works

The sort_items function uses getattr to fetch the sort attribute dynamically from each Item instance, based on the order_by parameter. Allowing only whitelisted field names prevents arbitrary attribute access and potential errors. The reverse flag flips the sort direction when the query parameter is 'desc', matching common API conventions. Using dataclasses keeps the data structure lightweight and readable.

Common mistakes

  • Letting user input access internal attributes like `_private_field` through `getattr` without a whitelist.
  • Case-sensitive comparison of direction (expecting 'DESC' to work).
  • Forgetting to validate the sort field before calling `sorted`, causing a generic AttributeError instead of a friendly 400 error.

Variations

  1. Use a lambda with explicit if/elif instead of `getattr` for more complex sort keys.
  2. Sort in-place with `list.sort()` if the original order is not needed.

Real-world use cases

  • Implementing a REST API endpoint like GET /items?order_by=price&direction=desc to let clients control response ordering.
  • Building an admin panel that sorts tables by clicking column headers, sending the sort field as a query parameter.
  • Sorting an in-memory cache or test fixture data in a deterministic order before asserting API responses.

Sponsored

Run this sample

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

Open editor

More from API design & gRPC

Related tutorials and quizzes for this topic.