Dictionary and set comprehensions
Overview
Just like `list` comprehensions, Python allows you to build dictionaries and sets using a concise one-line syntax. A dictionary comprehension uses curly braces with a key-value mapping: {key: value for item in iterable} A set comprehension uses curly braces with just a single expression: {expression for item in iterable} Think of them as a fast, readable factory pipeline that maps or filters data directly into a hashed lookup structure instead of a flat `list`. When creating a dictionary, if multiple items generate the same key, the last one evaluated overwrites previous values. pairs = [("a", 1), ("b", 2), ("a", 3)] # The second "a" overwrites the first merged = {k: v for k, v in pairs} print(merged) # {'a': 3, 'b': 2} This behavior is consistent with standard dictionary assignment. Overriding nested data structures during comprehensions is covered fully in nested-comprehensions.
When processing database rows or API results, you frequently need to index data by ID for fast `O(1)` lookups (instant retrieval regardless of size) later, or invert a mapping. Doing this with a standard `for` loop requires initializing an empty `dict` and repeatedly assigning keys. A comprehension does this in a single, highly readable expression.
Where used: Indexing a `list` of ORM objects by their primary key, Inverting mappings (swapping keys and values), Extracting unique tags from a `list`
Why learn this
- Quickly converting a `list` of API results into a dictionary indexed by ID
- Inverting an existing dictionary mapping in one line
- Filtering out duplicate values while transforming them
Code walkthrough
status_codes = {200: 'OK', 404: 'Not Found'}
inverted = {v: k for k, v in status_codes.items()}
print(inverted)
Focus: The `{v: k for k, v in ...}` pattern iterates over the key-value pairs and reverses them, instantly creating an inverted lookup table.
Common mistakes
- Confusing set and dict comprehensions: If you provide a colon (`key: value`), it's a `dict`. If you just provide a single expression, it generates a `set`.
- Un-hashable keys in dict comprehensions: The `key` expression in your loop must evaluate to an immutable type (like a `str` or `int`). If it evaluates to a `list` or `dict`, Python raises a `TypeError`.
Glossary
- comprehension
- A concise and highly readable way to create a new `list`, `dict`, or `set` by transforming or filtering an existing collection. Example: `{w: len(w) for w in words}`
- hashable
- An object that has a fixed value that never changes during its lifetime, allowing it to be used as a dictionary key or set item. Example: `'name'`
Recall questions
- What distinguishes a dict comprehension from a set comprehension syntactically?
- What happens if a dictionary comprehension generates the same key multiple times?
Understanding checks
What is the output of the following dictionary comprehension?
3
The dictionary comprehension maps each word to its length. Therefore, `lengths['bat']` evaluates to `3`.
A developer writes `{x for x in range(5)}` and thinks this evaluates to a dictionary because they used curly braces. Why are they incorrect?
Because the expression doesn't contain key-value pairs separated by a colon, it evaluates to a `set` comprehension, not a `dict`.
Curly braces denote both dictionaries and sets. If the comprehension has `key: value`, it's a `dict`. If it just has an expression, it's a `set`.
What is the output of this dictionary comprehension?
30
When a dictionary comprehension encounters duplicate keys, the last key-value pair evaluated overwrites previous values. The first value `10` is replaced by `30`.
Practice tasks
Index users and extract unique domains
Modify the `user_lookup` loop into a single dictionary comprehension that maps a user's `id` to the whole dictionary, and the `unique_domains` loop into a single `set` comprehension.
Challenge
Filter and index products
You are given a `list` of products. Create a `dict` mapping `product_id` to `name`, but ONLY for products that have `in_stock` set to `True`. Use a single `dict` comprehension with an `if` clause.
Continue learning
Previous: Dictionaries: operations and use cases
Previous: Sets: operations and use cases
Previous: List Comprehensions
Next: Nested comprehensions