Dict comprehensions

A concise way to build a new dictionary by transforming or filtering another collection.

Returns
A new dictionary.
Changes the original
No
On this page

Example

#
Python
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)
Resultsaved result, you can check it
{'Emma': 4, 'Jack': 4, 'Mia': 3}
{'Python': 39.5, 'React': 49.5}

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

#
Syntax
{key: value for item in collection if condition}

More examples

#
Swapping keys with values
Python
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()})
Resultsaved result, you can check it
{'Polish': 'pl', 'English': 'en'}
{5: 'Mia', 4: 'Jack'}
A dictionary from two lists and from a range
Python
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)})
Resultsaved result, you can check it
{'HTML': 11, 'CSS': 9, 'Python': 12}
{1: 1, 2: 4, 3: 9, 4: 16}

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

#

Spotted a mistake or missing an example? Write to us.