Dict comprehensions
A concise way to build a new dictionary by transforming or filtering another collection.
- Returns
- A new dictionary.
- Changes the original
- No
Example
#names = ["Emma", "Jack", "Mia"]
lengths = {name: len(name) for name in names}
print(lengths)
prices = {"HTML": 49, "Python": 79, "React": 99}
sale = {course: price * 0.5 for course, price in prices.items() if price > 50}
print(sale)Definition and usage
#A dict comprehension builds a dictionary following the pattern {key: value for item in collection}. It works like a list comprehension, except it is written inside curly braces, and a colon separates the key from the value.
An optional if condition at the end filters the items. The source can be any collection: a list, range(), pairs from zip(), or the items() of another dictionary. This lets you transform values, swap keys with values, or pick only some of the entries.
When two items produce the same key, the result keeps the value from the last one, with no warning at all. When you reverse a dictionary that has repeated values, part of the data simply disappears.
Syntax
#{key: value for item in collection if condition}More examples
#codes = {"pl": "Polish", "en": "English"}
print({name: code for code, name in codes.items()})
grades = {"Emma": 5, "Jack": 4, "Mia": 5}
print({grade: name for name, grade in grades.items()})courses = ["HTML", "CSS", "Python"]
modules = [11, 9, 12]
print({course: count for course, count in zip(courses, modules)})
print({n: n ** 2 for n in range(1, 5)})Good practices
#- For simply combining two lists,
dict(zip(keys, values))is enough. A dict comprehension is worth it when you also want to transform or filter along the way. - Watch out for repeated keys: the last value silently overwrites the earlier ones.
Related entries
#- List comprehensionsA concise way to build lists, sets, and dictionaries from other collections.
- dict.items()Returns a view of (key, value) pairs, the most convenient way to loop over a dictionary.
- zip()Pairs up (or groups into tuples) the matching items of several collections.
- dict()Creates a dictionary from key-value pairs or keyword arguments.
- forA loop that goes through the successive items of a sequence or other iterable object.
Spotted a mistake or missing an example? Write to us.