Meaning
This pattern creates a new dictionary whose keys are the original values and whose values are the original keys. It solves the problem of needing a reverse lookup when the original mapping is one-to-one. You reach for it whenever you have a dictionary and you need to look up the original key by its associated value.
Primary Function
Data transformation
Communicative Purpose
Enables quick inversion of a mapping dictionary for reverse lookup.
Pattern
inverted = {value: key for key, value in source_dict.items()}
Core Structure
inverted = {...: ... for ..., ... in ... .items()}
Função primária
Data transformation
Propósito comunicativo
Enables quick inversion of a mapping dictionary for reverse lookup.
Situações de gatilho
Data processing: swapping keys and values of a lookup table Web development: reversing a JSON mapping to retrieve original identifiers
Contextos
Python scripts, data analysis pipelines, web back‑ends, configuration management tools
Padrão
inverted = {value: key for key, value in source_dict.items()}
Estrutura central
inverted = {...: ... for ..., ... in ... .items()}
Slots de substituição
inverted: dict mapping values to keys, key: original key type, value: original value type, source_dict: dict of key→value
Colocados típicos
- .items()
- dict comprehension
- key‑value swap
Substituições comuns
- Use a for‑loop with assignment – clearer for beginners but more verbose Use zip with values and keys – `dict(zip(source_dict.values()
- source_dict.keys()))` – works only when values are unique and hashable Use `dict(map(reversed
- source_dict.items()))` – concise but less readable for novices
Erros comuns
Omitting `.items()` and iterating over the dictionary directly – results in iterating over keys only Assuming all values are unique – duplicate values cause later keys to overwrite earlier ones Using unhashable values (e.g., lists) as new keys – raises a TypeError at runtime Swapping in place without creating a new dict – leads to runtime errors due to changing size during iteration
Similar / contraste
List comprehension – produces a list, not a mapping `dict.update()` for merging – does not invert keys and values Using `defaultdict(list)` for reverse mapping when values are not unique
Interferências
Coming from JavaScript: assuming object literal inversion works the same – JavaScript objects do not preserve key order and require explicit iteration with `Object.entries` Coming from Java: expecting `Map` to allow duplicate values for reverse lookup – Python dicts will overwrite duplicates
Família do chunk
- dict comprehension
- key‑value swap
- reverse mapping
- dict.fromkeys
Nuance
Do not use when original values are not unique; you will lose data Performance is O(n) time and creates a new dict, incurring additional memory proportional to the original size All original values must be hashable; mutable types like lists cannot serve as keys in the inverted dict
Efeito pragmático
Provides an efficient way to implement reverse lookups, reducing boilerplate and potential bugs in code that needs to map values back to their original identifiers.
Dica de memória
Inverting a dictionary is like swapping name tags on a guest list so each person now wears the other's name.
Nota
If the original dictionary contains duplicate values, consider using `collections.defaultdict(list)` to collect all original keys under each value.
Upgrade path
Use collections.defaultdict(list) to build a reverse mapping that collects all original keys for each value when values are not unique, enabling a reverse multimap.
Log in to save chunks.