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.
Imagine an Indian merchant listing imported electronics on an e-commerce platform:
Visual Architecture Blueprint Copy Diagram +-------------------------------------------------------------------------+
| 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.
A dictionary comprehension uses curly braces {} enclosing a colon-separated key-value pair before the for clause:
1 { <Key Expression> : <Value Expression> for <item> in <iterable> if <Filter Predicate> }
2 ▲ ▲ ▲
3 │ │ │
4 New Dict Key New Dict Value Optional Filter
Essential Syntax Patterns: 1 Iterating over an existing dictionary:
{k: v * 2 for k, v in my_dict.items()}
1 Pairing two lists with zip():
{name: score for name, score in zip(names, scores)}
1 Filtering by key or value:
{k: v for k, v in data.items() if v >= 100}
1 Conditional values (Ternary):
{k: ("PASS" if v >= 40 else "FAIL") for k, v in marks.items()}
1 # Raw prices in USD for tech hardware
2 inventory_usd = {
3 "Laptop" : 850.0 ,
4 "Wireless Mouse" : 25.0 ,
5 "Mechanical Keyboard" : 75.0 ,
6 "4K Monitor" : 320.0 ,
7 "USB-C Hub" : 18.0
8 }
9
10 USD_TO_INR = 83.50
11 GST_RATE = 1.18
12
13 # Transform: uppercase keys, convert price to INR with GST included
14 catalog_inr = {
15 item . upper ( ) : round ( price * USD_TO_INR * GST_RATE , 2 )
16 for item , price in inventory_usd . items ( )
17 }
18
19 print ( "Original USD Inventory:" )
20 for k , v in inventory_usd . items ( ) :
21 print ( f" { k } : $ { v } " )
22
23 print ( "\nIndian Store Catalog (INR with 18% GST):" )
24 for k , v in catalog_inr . items ( ) :
25 print ( f" { k } : ₹ { v : ,.2f } " )
Expected Output:
1 Original USD Inventory:
2 Laptop: $850.0
3 Wireless Mouse: $25.0
4 Mechanical Keyboard: $75.0
5 4K Monitor: $320.0
6 USB-C Hub: $18.0
7
8 Indian Store Catalog (INR with 18% GST):
9 LAPTOP: ₹83,758.85
10 WIRELESS MOUSE: ₹2,463.25
11 MECHANICAL KEYBOARD: ₹7,389.75
12 4K MONITOR: ₹31,529.60
13 USB-C HUB: ₹1,773.54
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:
1 roll_numbers = [ "MSK-101" , "MSK-102" , "MSK-103" , "MSK-104" , "MSK-105" ]
2 student_names = [ "Aarav Sharma" , "Sneha Roy" , "Kabir Khan" , "Meera Iyer" , "Vikram Rathore" ]
3
4 # Create an O(1) lookup index mapping Roll Number -> Student Name
5 student_directory = { roll : name for roll , name in zip ( roll_numbers , student_names ) }
6
7 print ( "Generated Directory:" , student_directory )
8 print ( "Lookup for MSK-103 :" , student_directory . get ( "MSK-103" ) )
Expected Output:
1 Generated Directory: {'MSK-101': 'Aarav Sharma', 'MSK-102': 'Sneha Roy', 'MSK-103': 'Kabir Khan', 'MSK-104': 'Meera Iyer', 'MSK-105': 'Vikram Rathore'}
2 Lookup for MSK-103 : Kabir Khan
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):
1 # Original mapping: User -> Unique Assigned Token
2 user_tokens = {
3 "arjun" : 9811 ,
4 "divya" : 4520 ,
5 "rahul" : 3198 ,
6 "kavita" : 7721
7 }
8
9 # Invert dictionary: Token -> User
10 token_to_user = { token : user for user , token in user_tokens . items ( ) }
11
12 print ( "Original Mapping (User -> Token) :" , user_tokens )
13 print ( "Inverted Mapping (Token -> User) :" , token_to_user )
14
15 # Instant O(1) reverse lookup
16 query_token = 4520
17 print ( f"Token { query_token } belongs to : { token_to_user . get ( query_token ) } " )
Expected Output:
1 Original Mapping (User -> Token) : {'arjun': 9811, 'divya': 4520, 'rahul': 3198, 'kavita': 7721}
2 Inverted Mapping (Token -> User) : {9811: 'arjun', 4520: 'divya', 3198: 'rahul', 7721: 'kavita'}
3 Token 4520 belongs to : divya
Important Warning [!WARNING]
Duplicate Values During Inversion:
If multiple keys in the original dictionary share the same value (e.g., {"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 1 # Academic evaluation: assigning pass/fail status and distinction
2 subject_scores = {
3 "Mathematics" : 92 ,
4 "Physics" : 78 ,
5 "Chemistry" : 35 ,
6 "Computer Science" : 96 ,
7 "English" : 58
8 }
9
10 # Categorize performance: 'Distinction' (>= 90), 'Pass' (>= 40), or 'Fail' (< 40)
11 academic_status = {
12 subject : "Distinction" if mark >= 90 else ( "Pass" if mark >= 40 else "Fail" )
13 for subject , mark in subject_scores . items ( )
14 }
15
16 print ( "Marks Breakdown:" )
17 for subj , status in academic_status . items ( ) :
18 print ( f" { subj : <18 } : { subject_scores [ subj ] : >3 } marks ( { status } )" )
Expected Output:
1 Marks Breakdown:
2 Mathematics : 92 marks (Distinction)
3 Physics : 78 marks (Pass)
4 Chemistry : 35 marks (Fail)
5 Computer Science : 96 marks (Distinction)
6 English : 58 marks (Pass)
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
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).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:
1 inventory = {
2 "COTTON-01" : 450.0 ,
3 "SILK-99" : 2800.0 ,
4 "POLY-12" : 180.0 ,
5 "LINEN-44" : 1400.0 ,
6 "KHADI-07" : 320.0 ,
7 "VELVET-88" : 3500.0
8 }
Write a Python script that uses dictionary comprehensions to:
1 Filter out budget items below ₹300.
2 Apply 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). 1 Return a new dictionary where:
Key: The item code. Value: A formatted string ₹<Final Price> (<GST Slabs Rate>). Starter Code 1 inventory = {
2 "COTTON-01" : 450.0 ,
3 "SILK-99" : 2800.0 ,
4 "POLY-12" : 180.0 ,
5 "LINEN-44" : 1400.0 ,
6 "KHADI-07" : 320.0 ,
7 "VELVET-88" : 3500.0
8 }
9
10 # TODO: Write dictionary comprehension with filtering and tiered GST calculation
Complete Solution 1 inventory = {
2 "COTTON-01" : 450.0 ,
3 "SILK-99" : 2800.0 ,
4 "POLY-12" : 180.0 ,
5 "LINEN-44" : 1400.0 ,
6 "KHADI-07" : 320.0 ,
7 "VELVET-88" : 3500.0
8 }
9
10 # Dictionary comprehension: filter >= 300, apply tiered GST with ternary expression
11 taxed_catalog = {
12 code : (
13 f"₹ { price * 1.18 : .2f } (18% Luxury GST)"
14 if price >= 1500.0
15 else f"₹ { price * 1.05 : .2f } (5% Standard GST)"
16 )
17 for code , price in inventory . items ( )
18 if price >= 300.0
19 }
20
21 print ( "--- Surat Wholesale Taxed Fabric Catalog ---" )
22 for item_code , details in taxed_catalog . items ( ) :
23 print ( f" { item_code : <12 } : { details } " )
Expected Output 1 --- Surat Wholesale Taxed Fabric Catalog ---
2 COTTON-01 : ₹472.50 (5% Standard GST)
3 SILK-99 : ₹3304.00 (18% Luxury GST)
4 LINEN-44 : ₹1470.00 (5% Standard GST)
5 KHADI-07 : ₹336.00 (5% Standard GST)
6 VELVET-88 : ₹4130.00 (18% Luxury GST)
Interactive Quiz • Knowledge Check
Practice Quiz 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()
What is the output of the following dictionary comprehension?
Python Code Snippet
1 fruits = [ "apple" , "fig" , "banana" ]
2 result = { f : len ( f ) for f in fruits if len ( f ) > 3 }
3 print ( result )
A {'apple': 5, 'banana': 6}
B {'fig': 3}
C {'apple': 5, 'fig': 3, 'banana': 6}
D [5, 6]
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
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}
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]
In the next lesson, we will continue your intermediate Python journey with Nested Comprehensions (1: Advanced Data Types & Comprehensions).
👉 Continue to Next Lesson: Nested Comprehensions →