Build Python dictionaries with a comprehension, including filtering and transforming the values.
A dictionary comprehension builds a dict from an iterable in a single expression. The syntax is {key: value for item in iterable if condition}.
words = ["apple", "banana", "cherry", "date"]
# Key and value derived from the same item
lengths = {word: len(word) for word in words}
print(lengths) # {'apple': 5, 'banana': 6, 'cherry': 6, 'date': 4}
# Filter as you go
only_long = {word: len(word) for word in words if len(word) > 5}
print(only_long) # {'banana': 6, 'cherry': 6}
# Key and value from different places
pairs = [("a", 1), ("b", 2)]
print({key: value for key, value in pairs}) # {'a': 1, 'b': 2}The long-word filter leaves banana and cherry, since apple is five characters and date is four.
The key expression and the value expression are independent, so you can build a dictionary from pairs, transform the values, or reverse the key and the value. A common pattern is inverting a dictionary: {value: key for key, value in original.items()}.
Two details. Later duplicates win — if the iterable contains the same key twice, the last value is the one that ends up in the dictionary. And the key must be hashable, so building a dict with a list as the key raises a TypeError.
The comparison with the alternatives is worth making. Building the same thing in a loop means writing an empty dict, then a for statement with an assignment inside it — three lines instead of one, and the comprehension is faster because it avoids the repeated dictionary method lookups.