liveBook · Manning

Dictionary comprehension

As explained in Python Workout, Second Edition

A dict comprehension is Python syntax for constructing a dictionary by iterating over an iterable and computing key-value pairs, optionally subject to filtering.

A dictionary comprehension constructs a dictionary from an iterable by computing a key–value pair for each item. Its compact form separates key and value expressions with a colon. section 8.19

{ KEY : VALUE
  for ITEM in ITERABLE }

Use this pattern when the goal is a new dictionary derived from an iterable rather than commands or side effects. section 8.19

Work through the construction strategy:

  • Choose an iterable such as a string, list, tuple, dictionary, set, or file. section 8.19
  • Iterate over dictionary items for direct key–value unpacking, or iterate over keys and retrieve values separately. section 8.19
  • Prefer a regular for loop when the task is primarily about side effects rather than the resulting dictionary. section 8.19
  • Filter or transform source data while building dictionaries from configuration files, filenames, or structured records. section 8.33

Number the alphabet

Create a dictionary whose lowercase letters map to numbers from 1 through 26. Use enumerate with a starting value of 1 so the index matches the required numbering: {char: index for index, char in enumerate(string.ascii_lowercase, 1)}. section 8.31

Practice variations

Count vowels in each word, map filenames to file lengths, parse name=value configuration lines, discard non-integer values, or map city names to populations. section 8.21 section 8.33

How Python Workout, Second Edition covers it

How deep it goes
Explains syntax, iterable choices, dictionary iteration, unpacking, and loop selection, but does not develop advanced implementation internals.
Examples
Uses alphabet numbering, vowel counts, file lengths, configuration parsing, and city-population transformations as practice.
What it assumes
Assumes familiarity with Python iterables, dictionaries, for loops, unpacking, and basic string and file processing.
What you can do after
Build it from scratch by deriving key–value pairs from strings, files, dictionaries, configuration data, or structured records.
How it connects
Connects dictionary comprehensions with iterables, dictionary methods, parallel assignment, enumerate, string processing, files, 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 Workout, Second Edition. The section links point to the parts of the book it draws on.