1. Pythonic Data Structures & Comprehensions
Dict & Set Comprehensions, Generator Expressions & Star Unpacking
Write expressive, idiomatic Python transformations using dictionary and set comprehensions, memory-saving generator expressions, zip(), and extended star unpacking.
- Build and filter dictionaries and sets cleanly in one expression
- Choose generator expressions over list comprehensions when streaming large data
- Extract head, middle, and tail values cleanly using star unpacking and zip()
In Python Fundamentals, you learned how list comprehensions replace repetitive .append() loops. In real-world Python codebases, you will constantly see that same pattern extended to dictionaries, sets, lazy generator expressions, and extended unpacking.
Why It Matters: Before vs After
Beginners often write 5–8 lines of imperative loop boilerplate with temporary variables just to reshape a list of API records into a lookup table:
# Before: verbose imperative loop with manual filtering & mutation
paid_totals = {}
for order in orders:
if order["paid"]:
paid_totals[order["id"]] = round(order["total"] * 1.08, 2)
# After: single-pass dictionary comprehension (declarative & clear)
paid_totals = {
order["id"]: round(order["total"] * 1.08, 2)
for order in orders
if order["paid"]
}The comprehension version makes your intent ("build a mapping of paid order IDs to taxed totals") immediately obvious—and avoids mutating an empty container line by line.
1. Dictionary Comprehensions
Whenever you need to build a lookup table, invert a mapping, or transform values inside an existing dictionary, use `{key_expr: val_expr for item in iterable if condition}`:
prices_usd = {"keyboard": 80, "mouse": 30, "monitor": 250}
# Apply a 10% discount only to items over $50
discounted = {
item: round(price * 0.9, 2)
for item, price in prices_usd.items()
if price > 50
}
print(discounted) # {'keyboard': 72.0, 'monitor': 225.0}Mental Model: How Python Evaluates a Dict Comprehension
Read a comprehension in three steps—left-to-right isn't the execution order!
- Loop (
for item, price in prices_usd.items()): Pulls the next pair from the source. - Filter (
if price > 50): IfFalse, skip immediately to the next pair. - Evaluate & Insert (
item: round(...)): Compute the key and value and store them in the newdict. (If a key appears twice, the later value wins and overwrites the earlier entry.)
Common Real-World Patterns
- Indexing a list of records by ID for
O(1)instant lookup instead of slowO(n)linear scanning:
users = [
{"id": 101, "name": "Maya"},
{"id": 102, "name": "Liam"},
{"id": 103, "name": "Sam"},
]
users_by_id = {u["id"]: u["name"] for u in users}
print(users_by_id[102]) # Liam- Inverting keys and values (only safe when values are unique and hashable):
status_codes = {"OK": 200, "NOT_FOUND": 404}
code_to_name = {code: name for name, code in status_codes.items()}
print(code_to_name[404]) # NOT_FOUND2. Set Comprehensions
Replace [] with curly braces (supplying single values instead of key: value) to build a deduplicated set directly:
emails = ["Maya@Example.com", "liam@example.com", "maya@example.com "]
unique_domains = {email.strip().lower().split("@")[1] for email in emails}
print(unique_domains) # {'example.com'}Writing items = {} creates an empty dictionary, never an empty set! Always call set() when starting an empty set.
3. Generator Expressions: (...) vs [...]
Wrapping a comprehension in parentheses (...) instead of square brackets [...] tells Python not to build the whole list in memory. Instead, it creates a generator that produces one item at a time on demand:
# Builds a 1,000,000-item list in RAM just to sum it (wasteful!)
total_eager = sum([n * n for n in range(1_000_000)])
# Streams one square at a time using almost zero memory!
total_lazy = sum(n * n for n in range(1_000_000))When a generator expression is the only argument inside a function call like sum(...), any(...), all(...), or max(...), you don't need double parentheses—and any() / all() even short-circuit the moment the answer is known:
scores = [84, 91, 77, 95]
everyone_passed = all(s >= 70 for s in scores)
has_honors = any(s >= 95 for s in scores) # Stops as soon as it sees 95!4. Extended Star Unpacking & zip()
Python's * operator isn't just for *args in functions—it lets you unpack sequences of unknown length without brittle slice indexes like record[3:]:
record = ["2026-11-30", "ERROR", "auth", "Invalid", "token", "expired"]
date_str, level, service, *message_words = record
print(date_str) # 2026-11-30
print(level) # ERROR
print(message_words) # ['Invalid', 'token', 'expired']You can place *target at the start (*head, last = items), middle (first, *middle, last = items), or end—and *target always produces a list, even if it captures zero elements ([]).
Pairing parallel lists? Use zip() with strict=True (Python 3.10+) so mismatched lengths raise ValueError immediately instead of silently dropping trailing items:
names = ["Maya", "Liam"]
scores = [94, 88]
leaderboard = {name: score for name, score in zip(names, scores, strict=True)}
print(leaderboard) # {'Maya': 94, 'Liam': 88}Decision Table & Common Pitfalls
| Syntax / Tool | Output Type | Memory & Behavior | Best Used When |
|---|---|---|---|
[x for x in src] | list | Eager; builds full list in RAM | You need indexing, len(), or multiple loops |
{k: v for k, v in src} | dict | Eager; overwrites duplicate keys | Building fast O(1) lookup tables |
{x for x in src} | set | Eager; deduplicates hashable items | Collecting unique normalized tags/domains |
(x for x in src) | generator | Lazy; yields one item at a time | Single-pass sum(), any(), all(), streaming |
If a comprehension needs nested if/else chains or two complex loops, switch back to a clean for loop or helper function. Concise code is great; clever unreadable one-liners are a maintenance trap.
Try It Yourself in the Playground
Experiment with dict/set comprehensions, lazy any()/all(), and star unpacking below:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Given words = ["alpha", "beta", "apricot", "berry", "avocado"], write a dictionary comprehension that maps each word to its character length only if the word starts with "a".
Quick Checkpoints
What is the biggest advantage of sum(x * 2 for x in range(10_000_000)) over sum([x * 2 for x in range(10_000_000)])?
After running head, *body, tail = [10, 20, 30, 40, 50], what is body?