liveBook · Manning

Dictionary comprehension

As explained in Python How-To

A dictionary comprehension is Python syntax for constructing a dictionary by iterating over an iterable and optionally filtering or transforming items into key-value pairs.

Dictionary comprehension is a concise Python pattern for creating a dictionary from an iterable. It places key and value expressions before the iteration: {expr_key: expr_value for item in iterable}. section 5.2.2

Build a title-to-description dictionary

When each task should be indexed by title, use the title as the key and the description as the value: title_dict = {task.title: task.description for task in tasks} This produces the same dictionary as a conventional loop while making the key-value mapping immediately visible. section 5.2.2

title_dict0 = {}
for task in tasks:
    title_dict0[task.title] = task.description
  
title_dict1 = {task.title: task.description for task in tasks}
 
assert title_dict0 == title_dict1

Compare the conventional loop with its equivalent dictionary comprehension and verify that both produce the same result. section 5.2.2

Use dictionary comprehension when:

  • An existing iterable must become a dict and its items need transformation into keys and values. section 5.2.2
  • The compact expression remains clear to the intended readers; its concision can improve readability for experienced Python users. section 5.2.2
  • Prefer a dict constructor when no item manipulation is needed, and use a regular for loop when expressions become complicated or loops become deeply nested. section 5.5 section 5.2.6

The pattern follows the broader comprehension family: list comprehensions create lists, dictionary comprehensions create dicts, and set comprehensions create sets. Each iterates an iterable while applying its respective construction syntax. section 5.2 section 5.2.6

How Python How-To covers it

How deep it goes
Defines key-value syntax, compares it with a loop, and defers complicated expressions or nested iteration to conventional loops.
Examples
Demonstrates mapping task titles to descriptions and contrasts the comprehension with an equivalent loop.
What it assumes
Assumes familiarity with Python dictionaries, iterables, and for-loop iteration while reinforcing container construction from existing iterables.
What you can do after
Apply it to build readable dictionaries from existing iterables and choose loops when comprehension complexity harms clarity.
How it connects
Connects dictionary comprehensions with iterables, list comprehensions, set comprehensions, dictionary constructors, and for loops.

Also explained in

Compare how 3 books explain dictionary comprehension →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.