Dict and set comprehension
- Python course
- Beginner
- Lesson 61/116
- 5 min
Learn {k: v for ...} and {x for ...}.
Dict comprehension
A dict comprehension builds a dictionary in one line. It uses curly braces and a colon:
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}. The key and value are computed for each item. If a key appears twice, the later one overwrites the earlier.
Set comprehension
A set comprehension also uses curly braces but no colon:
unique = {x % 3 for x in [1, 2, 4, 7]}
# {0, 1, 2}The result is a set: each value appears once. The only difference from a list comprehension is the curly brackets.
A set is unordered and unique; if order matters, use a list.
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
# Build a squares dict with a 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 Which is a dict comprehension?
- [k: v for k, v in pairs]
- (k: v for k, v in pairs)
- {k: v for k, v in pairs} Correct answer
- <k, v for k, v in pairs>
Explanation: Curly braces and a colon mark a dict comprehension.
2 Match the comprehension types
| Term | Meaning |
|---|---|
[...] |
List |
{k: v} |
Dict |
{x} |
Set |
(...) |
Generator |
3 Complete the set comprehension
unique = {x % 3 for x in [____, 2, 4, 7]}
unique = {x % 3 for x in [1, 2, 4, 7]}
Explanation: [1, 2, 4, 7] is the list, x % 3 gives the remainders.