Skip to main content
Module 6 · Lesson 2 of 422/36 in the course~14 min
Module lessons (2/4)

Dict and set comprehensions

Lesson preview5 hands-on exercises readyPython Course · Module 6 — Comprehensions and iteration

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

  1. 1The mental model: the colon : decides between dict and set
  2. 2Dict comprehension: transform, invert and filter maps
  3. 3Set comprehension and key collisions
  4. 4Quick check
  5. 5Test yourself
Pro Lesson · Module 6 — Comprehensions and iteration

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.