How to Sort a List of Dictionaries by Key in Python

A reusable helper function that sorts a list of dictionaries by a specified key, with optional descending order support.

Easy Python 3.9+ Aug 9, 2026 Data pipelines & processing 12 views 0 copies

Python code

37 lines
Python 3.9+
from typing import List

def sort_records(records: List[dict], key: str, descending: bool = False) -> List[dict]:
    """Sort a list of dictionaries by a specified key."""
    return sorted(records, key=lambda record: record[key], reverse=descending)


def demonstrate_sorting() -> None:
    users = [
        {"name": "Alice", "age": 34, "score": 88.5},
        {"name": "Bob", "age": 27, "score": 92.0},
        {"name": "Charlie", "age": 29, "score": 76.3},
        {"name": "Diana", "age": 31, "score": 95.1},
    ]

    print("Original records:")
    for user in users:
        print(user)

    print("\nSorted by age (ascending):")
    sorted_by_age = sort_records(users, "age")
    for user in sorted_by_age:
        print(user)

    print("\nSorted by score (descending):")
    sorted_by_score = sort_records(users, "score", descending=True)
    for user in sorted_by_score:
        print(user)

    print("\nSorted by name (ascending):")
    sorted_by_name = sort_records(users, "name")
    for user in sorted_by_name:
        print(user)


if __name__ == "__main__":
    demonstrate_sorting()

Output

stdout
Original records:
{'name': 'Alice', 'age': 34, 'score': 88.5}
{'name': 'Bob', 'age': 27, 'score': 92.0}
{'name': 'Charlie', 'age': 29, 'score': 76.3}
{'name': 'Diana', 'age': 31, 'score': 95.1}

Sorted by age (ascending):
{'name': 'Bob', 'age': 27, 'score': 92.0}
{'name': 'Charlie', 'age': 29, 'score': 76.3}
{'name': 'Diana', 'age': 31, 'score': 95.1}
{'name': 'Alice', 'age': 34, 'score': 88.5}

Sorted by score (descending):
{'name': 'Diana', 'age': 31, 'score': 95.1}
{'name': 'Bob', 'age': 27, 'score': 92.0}
{'name': 'Alice', 'age': 34, 'score': 88.5}
{'name': 'Charlie', 'age': 29, 'score': 76.3}

Sorted by name (ascending):
{'name': 'Alice', 'age': 34, 'score': 88.5}
{'name': 'Bob', 'age': 27, 'score': 92.0}
{'name': 'Charlie', 'age': 29, 'score': 76.3}
{'name': 'Diana', 'age': 31, 'score': 95.1}

How it works

The sorted() function returns a new list and leaves the original untouched, which is ideal for data pipelines. The key=lambda record: record[key] tells Python to extract the sort value from each dictionary. The reverse parameter flips the order to descending when set to True. Type hints (List[dict], str, bool) make the helper self-documenting and friendly for static checkers.

Common mistakes

  • Using `.sort()` on the original list, which mutates source data and may break downstream pipeline steps
  • Forgetting to handle missing keys — `record[key]` raises `KeyError` when the key is absent
  • Assuming decimal and string values sort the same way without normalizing types first

Variations

  1. Use `operator.itemgetter(key)` as a faster `key` argument instead of a lambda
  2. Sort in-place with `records.sort(key=..., reverse=...)` if mutation is acceptable and memory matters

Real-world use cases

  • Ordering API response rows by a timestamp or priority field before writing them to a database table.
  • Ranking customer records by a computed score in an ETL batch before sending to a reporting dashboard.
  • Sorting log entries or event payloads by severity or time so downstream aggregations process them in order.

Sponsored

Run this sample

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

Open editor

More from Data pipelines & processing

Related tutorials and quizzes for this topic.