Module lessons (2/4)
Dict and set comprehensions
Using {k: v for ...} and {x for ...} syntax to build dictionaries and sets declaratively.
What you'll learn in this lesson
- Building dictionaries declaratively with
{k: v for item in iter if cond}. - Construct deduplicated sets declaratively with
{expr for item in iter if cond}. - Prevent silent overwrites when derived keys collide in a dict comprehension.
Overview
The braces {...} transform the same syntax of comprehensions into expressive tools for building dictionaries and sets: it is the presence or absence of the colon : in the initial expression that communicates to the Python parser whether to produce a dict or a set.
Just like static literals, {k: v for ...} generates a key -> value hash table while {expr for ...} generates a duplicate-free mathematical set. The trailing if clauses work identically to filter inputs before insertion.
Sections covered in this lesson
- 1The mental model: the colon
:decides betweendictandset - 2Dict comprehension: transform, invert and filter maps
- 3Set comprehension and key collisions
- 4Quick check
- 5Test yourself
Unlock "Dict and set comprehensions" and the full Python Course curriculum
Using {k: v for ...} and {x for ...} syntax to build dictionaries and sets declaratively.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Python Course plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.