Dict comprehension
- Python course
- Beginner
- Lesson 69/116
- 4 min
Learn dict comprehensions with {k: v for ...}.
Dict comprehension
A dict comprehension is a short way to build a dict in one line:
squares = {n: n * n for n in [1, 2, 3]}
# {1: 1, 2: 4, 3: 9}The shape is: {key: value for variable in list}. You can add a filter with if condition at the end. This is shorter and more readable than a classic loop.
If a key appears twice, the later value overwrites the earlier one.
Filtered dict comprehension
You can filter pairs by adding if to a dict comprehension:
even_squares = {n: n * n for n in [1, 2, 3, 4] if n % 2 == 0}
# {2: 4, 4: 16}This is the same filter logic as in a list comprehension: only items matching the condition enter the result.
On big datasets this method is very short and fast.
Practice Write a squares dict
Assign to squares a dict comprehension that holds n: n * n pairs for each n in [1, 2, 3, 4]. Then print print(squares).
Starter code
# Squares with a dict comprehensionSample solution
squares = {n: n * n for n in [1, 2, 3, 4]}
print(squares)Expected output
{1: 1, 2: 4, 3: 9, 4: 16}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the dict comprehension
squares = {n: n * ____ for n in [1, 2, 3]}
squares = {n: n * n for n in [1, 2, 3]}
Explanation: n * n gives the square for each n.
2 What does {n: n * 2 for n in [1, 2, 3]} produce?
- [2, 4, 6]
- {2, 4, 6}
- {1: 2, 2: 4, 3: 6} Correct answer
- (1, 2, 3)
Explanation: Each n is doubled: {1: 2, 2: 4, 3: 6}.
3 Match the comprehension types
| Term | Meaning |
|---|---|
[...] |
List |
(...) |
Tuple/Generator |
{...} |
Set/Dict |
{k: v} |
Dict |