How to Index a List of Records by Unique ID in Python

Build a dictionary that maps each record's unique id to the record itself from a list of dictionaries.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 15 views 0 copies

Python code

15 lines
Python 3.9+
from typing import List, Dict, Any

def index_by_id(records: List[Dict[str, Any]], id_field: str = "id") -> Dict[Any, Dict[str, Any]]:
    """Build a dictionary mapping each record's unique id to the record itself."""
    return {record[id_field]: record for record in records}

if __name__ == "__main__":
    sample_records = [
        {"id": 101, "name": "Alice", "score": 92},
        {"id": 102, "name": "Bob", "score": 87},
        {"id": 103, "name": "Carol", "score": 95},
    ]
    indexed = index_by_id(sample_records)
    for key in sorted(indexed):
        print(f"{key}: {indexed[key]}")

Output

stdout
101: {'id': 101, 'name': 'Alice', 'score': 92}
102: {'id': 102, 'name': 'Bob', 'score': 87}
103: {'id': 103, 'name': 'Carol', 'score': 95}

How it works

The dictionary comprehension {record[id_field]: record for record in records} iterates over each record and uses its id field as the key, assigning the entire record as the value. This creates a direct mapping from id to record, allowing O(1) lookups instead of scanning the list every time. The id_field parameter defaults to "id" but can be changed to any field name in the records. Assuming ids are unique, this index is lossless — no records are overwritten. For non-unique ids, later records silently overwrite earlier ones, so validate uniqueness if needed.

Common mistakes

  • Assuming ids are unique — duplicates silently overwrite earlier records.
  • Forgetting to handle missing id keys with a KeyError.
  • Using the record itself as value, which may be too heavy for large datasets.
  • Not sorting keys when printing if deterministic order is required.

Variations

  1. Use `defaultdict(list)` to group records by id when ids are not unique.
  2. Use `dict.fromkeys` with a comprehension to initialize an index with default values.

Real-world use cases

  • Lookup customer records by customer_id in a user-facing API endpoint.
  • Build an in-memory index of database rows for quick joins between two datasets.
  • Maintain a cache of configuration items keyed by their unique config id.

Sponsored

Run this sample

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

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.