Use a dictionary comprehension when an iterable should become a dictionary of calculated key-value pairs. It iterates over source items, evaluates a key expression and a value expression, and creates one pair per iteration. section 7.22
{ KEY : VALUE
for ITEM in ITERABLE }
The core form is { KEY : VALUE for ITEM in ITERABLE }; the colon separates independently evaluated key and value expressions. section 7.22
For example, transforming a directory listing into filename-to-longest-word results separates the input collection from the calculation: each filename becomes a key, while find_longest_word(filename) supplies its value. section 5.17
Map filenames to their longest words
def find_all_longest_words(directory): filenames = os.listdir(directory) return { filename: find_longest_word(os.path.join(directory, filename)) for filename in filenames } The comprehension creates the dictionary; find_longest_word can scan each file line by line rather than loading an entire file into memory. section 5.16 section 5.17
Common patterns include:
- Iterate through d.items() to unpack each key and value, then construct a new dictionary. section 7.22
- Transform values while retaining keys by applying a function to each value. section 7.27
- Filter output pairs with a condition, such as excluding comments or non-integer configuration values. section 7.30 section 7.40
- Combine enumerate with string.ascii_lowercase to create letter-to-number mappings. section 7.37
Choose a comprehension when the goal is to create a new object from returned values. Prefer a regular for loop when the main purpose is commands or side effects, such as inserting records into a database. section 7.22


