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


