Dictionary Comprehensions in Python
Dictionary Comprehensions in Python
Dictionaries are Python's most ubiquitous mapping data structure, providing fast $O(1)$ average-time key lookups. In data transformation pipelines, you frequently need to re-index data, filter by thresholds, swap keys and values, or compute derived metrics from raw key-value pairs.
A Dictionary Comprehension provides a compact, expressive syntax to construct, filter, and transform dictionaries from any iterable.
Real-World Analogy: E-Commerce Currency Converter & Catalog Inverter
Imagine an Indian merchant listing imported electronics on an e-commerce platform:
+-------------------------------------------------------------------------+
| E-COMMERCE CATALOG CONVERTER ENGINE |
+-------------------------------------------------------------------------+
| |
| Raw USD Catalog: {"SKU-A": 100, "SKU-B": 250, "SKU-C": 40} |
| │ |
| ▼ |
| [ Dict Comprehension Engine: Apply Forex Rate (₹85) ] |
| [ + Add 18% GST ] |
| │ |
| ▼ |
| Indian Rupee Store: {"SKU-A": 10030, "SKU-B": 25075, "SKU-C": 4012} |
| |
+-------------------------------------------------------------------------+Rather than creating an empty dictionary, writing a manual for loop, and performing repeated key assignments, a single dictionary comprehension transforms the catalog in one line at C-level speed.
Technical Syntax Architecture
A dictionary comprehension uses curly braces {} enclosing a colon-separated key-value pair before the for clause:
Essential Syntax Patterns:
- 1Iterating over an existing dictionary:
{k: v * 2 for k, v in my_dict.items()}
- 1Pairing two lists with
zip():
{name: score for name, score in zip(names, scores)}
- 1Filtering by key or value:
{k: v for k, v in data.items() if v >= 100}
- 1Conditional values (Ternary):
{k: ("PASS" if v >= 40 else "FAIL") for k, v in marks.items()}
Comprehensive Code Examples
1. Key-Value Transformation & Currency Calculation
Expected Output:
2. Pairing Parallel Lists with zip()
When data arrives in parallel sequences (e.g. database column arrays), pair them directly using zip() inside a dictionary comprehension:
Expected Output:
3. Swapping Keys and Values (Dictionary Inversion)
Swapping keys and values enables reverse lookups (e.g. looking up a user name from an email address or user ID):
Expected Output:
{"A": 1, "B": 1}), inverting it causes the second key to overwrite the first ({1: "B"}). Ensure values are unique before inverting, or group them into lists.4. Conditional Values with Ternary Expressions
Expected Output:
Best Practices & Comparison: Do's and Don'ts
| Practice | Bad / Anti-Pattern | Recommended Gold Standard |
|---|---|---|
| Dictionary Iteration | {k: dict[k] for k in dict.keys()} | {k: v for k, v in dict.items()} |
| Pairing Sequences | Index looping: {keys[i]: vals[i] for i in range(len(keys))} | Use zip(): {k: v for k, v in zip(keys, vals)} |
| Filtering | Creating dict then deleting with del d[k] | Filter directly during comprehension with if |
| Key Collision | Inverting non-unique values blindly | Check uniqueness or aggregate collisions into lists |
| Readability | Nesting 3 levels of dict comprehensions | If comprehension spans > 3 lines, break into helper functions |
Quick Revision Summary Cheat Sheet
- Basic Syntax:
{key_expr: value_expr for item in iterable if condition} .items()Method: Always unpack key and value simultaneously:for k, v in my_dict.items().- Parallel Sequences: Pair lists together with
{k: v for k, v in zip(keys, values)}. - Inversion:
{v: k for k, v in d.items()}(last-write-wins for duplicate values). - Ternary Value Syntax:
{k: (val_true if cond else val_false) for k in iter}. - Hashability: Dictionary keys must be immutable and hashable (
str,int,tuple).
Multiple Choice Questions
1. What method must be invoked on a dictionary to unpack both key and value inside a comprehension?
A. d.values() B. d.keys() C. d.items() D. d.entries() Answer: C Explanation: Calling d.items() returns an iterable of (key, value) tuples, enabling simultaneous unpacking: for k, v in d.items(). Calling just for k in d: only yields keys.
2. What is the output of the following dictionary comprehension?
A. {'apple': 5, 'banana': 6} B. {'fig': 3} C. {'apple': 5, 'fig': 3, 'banana': 6} D. [5, 6] Answer: A Explanation: The if len(f) > 3 condition discards "fig" (length 3). The remaining items are "apple" (length 5) and "banana" (length 6), forming {'apple': 5, 'banana': 6}.
3. What happens if you invert a dictionary {v: k for k, v in d.items()} when multiple keys have the same value?
A. Python raises a DuplicateValueError B. All keys are collected into a set automatically C. The later key encountered during iteration overwrites the earlier key for that value D. The dictionary is deleted Answer: C Explanation: Dictionary keys must be unique. When duplicate values become keys, subsequent assignments overwrite prior assignments, resulting in only the last key associated with that value surviving.
4. Which of the following correctly pairs two lists into a dictionary?
A. {k, v for k, v in list1 + list2} B. {k: v for k, v in zip(list1, list2)} C. dict(list1 + list2) D. {k: v for k in list1 for v in list2} Answer: B Explanation: The zip(list1, list2) function pairs corresponding elements from both sequences as tuples (k, v), which can then be cleanly unpacked into a dictionary comprehension {k: v for k, v in zip(list1, list2)}.
5. What is the output of {x: x**2 for x in (1, 2, 3) if x % 2 != 0}?
A. {1: 1, 2: 4, 3: 9} B. {1: 1, 3: 9} C. {2: 4} D. [1, 9] Answer: B Explanation: The condition x % 2 != 0 filters for odd numbers. From (1, 2, 3), 1 and 3 are odd. Squaring them yields {1: 1, 3: 9}.
Practice Challenge
Scenario: Indian Retail Store GST Tax Classifier & Threshold Filter
A wholesale distributor in Surat sells fabric rolls. You are provided with a dictionary of item codes and their base wholesale prices in INR:
Write a Python script that uses dictionary comprehensions to:
- 1Filter out budget items below ₹300.
- 2Apply tiered GST rates:
- Items with base price $\ge$ ₹1,500 are considered luxury fabrics $\to$ apply 18% GST (
price * 1.18). - Items with base price $<$ ₹1,500 get standard 5% GST (
price * 1.05).
- 1Return a new dictionary where:
- Key: The item code.
- Value: A formatted string
₹<Final Price> (<GST Slabs Rate>).
Starter Code
Complete Solution
Expected Output
Nested Comprehensions
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Set Comprehensions | Nested Comprehensions |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.