Build Python dictionaries with a comprehension, including filtering and transforming the values.
A dictionary comprehension builds a whole dictionary from another collection in a single expression. The shape of it is {key: value for item in iterable if condition}.
words = ['apple', 'banana', 'cherry', 'date']
# The key and the value come from the same item.
lengths = {}
for word in words:
lengths[word] = len(word)
print(lengths)
# The same thing written as a comprehension.
lengths = {word: len(word) for word in words}
print(lengths)
# You can filter as you go.
only_long = {word: len(word) for word in words if len(word) > 5}
print(only_long)
# The key and the value can come from different places.
pairs = [('a', 1), ('b', 2)]
result = {}
for key, value in pairs:
result[key] = value
print(result)
The filter keeps Banana and Cherry, because Apple has five letters and Date has four.
The key part and the value part are independent of each other, so you can build a dictionary from pairs, you can change the values, and you can even turn the values into the keys. A common pattern is inverting a dictionary, which writes {value: key for key, value in original.items()}.
There are two details to remember. If the same key appears twice in the collection, the last value is the one that ends up in the dictionary, because each new value overwrites the older one. And the key has to be something that Python can hash, so building a dictionary with a list as the key raises a TypeError.
The comparison with the older way of doing this is worth making. Doing the same work in a loop means writing an empty dictionary, then a for statement, and then an assignment on the line inside it. That is three lines instead of one, and the comprehension is also a little faster because it avoids looking up the dictionary method again and again.