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.
Python code
15 linesfrom 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
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
- Use `defaultdict(list)` to group records by id when ids are not unique.
- 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
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.