Dict and set comprehensions

Comprehensions & Iteration, lesson 2 of 5

⚡ 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?

Example

Set comprehension

A set drops the duplicates for you: 4 emails, 2 domains.

Quiz

What does this print?

Exercise

Grade report

Use comprehensions to build:

  1. passed: a dict of only the students who scored 60 or more (name → score).
  2. status: a dict mapping every name to "pass" or "fail" (60 is a pass).
  3. initials: a set of the first letter of each name.