Meaning
This pattern ensures that a key in a dictionary maps to a list, creating the list if the key is missing, then appends a value to that list. It is useful for grouping items by a key without checking if the key exists first.
Primary Function
Data collection
Communicative Purpose
Build a dictionary where each key maps to a list of values, avoiding KeyError.
Pattern
mapping.setdefault(key, []).append(value)
Core Structure
mapping.setdefault(...).append(...)
Função primária
Data collection
Propósito comunicativo
Build a dictionary where each key maps to a list of values, avoiding KeyError.
Situações de gatilho
Data processing: accumulating values per key while iterating over records; Graph algorithms: building adjacency lists from edge lists; Mapping inversion: creating reverse lookup where each value maps to a list of original keys
Contextos
Common in data processing scripts, ETL pipelines, graph building, and any code that aggregates items by category.
Padrão
mapping.setdefault(key, []).append(value)
Estrutura central
mapping.setdefault(...).append(...)
Slots de substituição
mapping: dict-like object; key: hashable; value: any object to append.
Colocados típicos
- Often used with for loops
- defaultdict
- groupby
- itertools.
Substituições comuns
- Using collections.defaultdict(list) and then mapping[key].append(value)
- or using dict.get(key
- []) + [value] reassignment.
Erros comuns
Forgetting that setdefault returns the list, leading to missing append; using mutable default argument incorrectly; calling setdefault with a non-list default causing TypeError.
Similar / contraste
dict.get(key, []) + [value] creates a new list each time, less efficient; defaultdict automatically creates missing keys.
Interferências
Coming from languages where hash maps auto-create containers (e.g., PHP, JavaScript), may expect similar behavior without explicit setdefault.
Família do chunk
- dict.setdefault
- defaultdict
- grouping patterns.
Nuance
The pattern creates a new list only when the key is missing; if the key already maps to a non-list, AttributeError will occur. Not thread-safe.
Efeito pragmático
Eliminates boilerplate key-existence checks and prevents KeyError.
Dica de memória
Set default, then add.
Nota
Equivalent to using collections.defaultdict(list) for the whole dictionary.
Upgrade path
Use collections.defaultdict or dict comprehensions for bulk building.
Log in to save chunks.