Dictionary Comprehension
Dictionary comprehension provides a concise way to create dictionaries using a syntax similar to list and set comprehensions, but with key-value pairs separated by a colon.
Basic Syntax
The general form of dictionary comprehension is:
{exp1: exp2 for var in iter [if condition][...dict comp]}Where:
exp1is the expression for the keyexp2is the expression for the valuevaris the variable that iterates over the iterableiteris the iterable (list, range, etc.)if conditionis optional - filters elements- Additional dictionary comprehensions are optional - for nested iterations
Simple Dictionary Comprehension
The simplest form creates a dictionary by mapping keys to values:
d1 = {n: n * 2 for n in range(3)}print(d1) # {0: 0, 1: 2, 2: 4}This creates a dictionary where each number maps to its double.
Dictionary Comprehension with Condition
You can add a condition to filter key-value pairs:
d2 = {n: n * 2 for n in range(3) if n > 0}print(d2) # {1: 2, 2: 4}This only includes entries where n > 0, so it skips n = 0.
Copying a Dictionary
You can use dictionary comprehension to create a copy of a dictionary:
d1 = {0: 0, 1: 2, 2: 4}d3 = {k: v for k, v in d1.items()}print(d3) # {0: 0, 1: 2, 2: 4}Nested Dictionary Comprehension
You can use multiple for clauses to create nested iterations:
d1 = {0: 0, 1: 2, 2: 4}d2 = {1: 2, 2: 4}d4 = {m: m + n for m in d1.values() for n in d2.values()}print(d4) # {0: 4, 2: 6, 4: 8}This creates a dictionary where keys come from d1.values() and values are the sum of a key from d1.values() and a value from d2.values().
Multiple Conditions
You can have multiple conditions and multiple loops:
d5 = {m: n for m in range(-4, 4) if m % 2 == 0 for n in range(-4, 4) if n % 2 == 1}print(d5) # {-4: 3, -2: 3, 0: 3, 2: 3}This:
- Iterates over
mfrom -4 to 3, but only whenm % 2 == 0(even numbers) - For each
m, iterates overnfrom -4 to 3, but only whenn % 2 == 1(odd numbers) - Creates key-value pairs where the key is
mand the value isn
Note: If multiple n values satisfy the condition for the same m, only the last one is kept (dictionaries can’t have duplicate keys).
Exercises
Exercise 1: Basic Dictionary Comprehension
Use dictionary comprehension to create a dictionary mapping numbers from 0 to 9 to their squares.
Basic Dictionary Comprehension
squares = {n: n * n for n in range(10)}print(squares)Exercise 2: Dictionary Comprehension with Condition
Use dictionary comprehension to create a dictionary mapping even numbers from 0 to 20 to their halves.
Dictionary Comprehension with Condition
halves = {n: n // 2 for n in range(21) if n % 2 == 0}print(halves)Exercise 3: Transforming Keys and Values
Given a list of strings, use dictionary comprehension to create a dictionary mapping each string to its length.
Transforming Keys and Values
n = int(input())words = []for i in range(n): words.append(input())
lengths = {word: len(word) for word in words}print(lengths)Exercise 4: Nested Dictionary Comprehension
Use nested dictionary comprehension to create a dictionary where keys are pairs (i, j) and values are i * j, for i and j from 0 to 2.
Nested Dictionary Comprehension
products = {(i, j): i * j for i in range(3) for j in range(3)}print(products)Exercise 5: Filtering Dictionary Entries
Given a dictionary, use dictionary comprehension to create a new dictionary containing only entries where the value is greater than 10.
Filtering Dictionary Entries
n = int(input())original = {}for i in range(n): key = i value = int(input()) original[key] = value
filtered = {k: v for k, v in original.items() if v > 10}print(filtered)