⚡ Comprehensions & Iteration, lesson 2 of 5
Dict and set comprehensions
Build dictionaries and sets with the same one-line syntax.
9 min
1 exercise
2 quizzes
0/3 solved
Getting Python ready… examples can run in a moment.
The comprehension trick works for dicts and sets too, using curly braces:
{key: value for item in iterable} # dict
{expression for item in iterable} # set
The if filter works exactly like in list
comprehensions.
Example
Price list makeover
Make a dict of the items that cost more than 2.75.
Example
Lookups and flips
Swapping keys and values makes a reverse lookup table.
Quiz
What does this print?
{1: 1, 2: 4, 3: 9}
{1: 2, 2: 4, 3: 6}
[1, 4, 9]
{0: 0, 1: 1, 2: 4}
Example
Set comprehension
A set drops the duplicates for you: 4 emails, 2 domains.
Quiz
What does this print?
2
4
3
1
Exercise
Grade report
Use comprehensions to build:
passed: a dict of only the students who scored 60 or more (name → score).status: a dict mapping every name to"pass"or"fail"(60 is a pass).initials: a set of the first letter of each name.