Statement

dict comprehension

A dict comprehension builds a new dictionary in one line from any collection, choosing each key and value, with an optional filter.

IntermediateEvery example below runs in your browser. Change the code and press Run.

{key_expression: value_expression for item in iterable} {key: value for item in iterable if condition}

A dict comprehension works like a list comprehension, but with curly braces and a key: value pair at the front. Every round of the loop adds one entry to the new dictionary.

It is handy for turning two lists into a dictionary, flipping keys and values, changing all values (for example converting prices), or keeping only the entries you need.

If two rounds produce the same key, the later value wins and the earlier one is lost. Dictionaries keep the order in which keys were first added.

Return value

A new dictionary.

Examples

1Squares as a dictionary

Pythoneditable
squares = {n: n * n for n in range(1, 6)}
print(squares)
Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

2Two lists into one dictionary

Pythoneditable
names = ["Ava", "Ben", "Cleo"]
scores = [88, 72, 95]
results = {name: score for name, score in zip(names, scores)}
print(results)
Output
{'Ava': 88, 'Ben': 72, 'Cleo': 95}

dict(zip(names, scores)) does the same; the comprehension lets you change the values on the way.

3Change every value

Pythoneditable
prices_eur = {"coffee": 3.0, "bagel": 2.5, "juice": 4.2}
prices_usd = {item: round(p * 1.08, 2) for item, p in prices_eur.items()}
print(prices_usd)
Output
{'coffee': 3.24, 'bagel': 2.7, 'juice': 4.54}

4Keep only some entries

Pythoneditable
stock = {"apples": 12, "pears": 0, "plums": 5, "figs": 0}
available = {fruit: n for fruit, n in stock.items() if n > 0}
print(available)
Output
{'apples': 12, 'plums': 5}

5Flip keys and values

Pythoneditable
codes = {"GR": "Greece", "PT": "Portugal", "JP": "Japan"}
by_name = {country: code for code, country in codes.items()}
print(by_name["Japan"])
Output
JP

Common mistakes

Duplicate keys overwrite each other

When two items give the same key, only the last one survives. Here two words start with "b".

Pythoneditable
words = ["apple", "banana", "blueberry"]
first_letter = {w[0]: w for w in words}
print(first_letter)
Output
{'a': 'apple', 'b': 'blueberry'}

Forgetting the colon makes a set

{x for x in items} without key: value is a set comprehension, not a dictionary.

Questions people ask

How do I create a dictionary from a list?

Choose a key for each item: {name: len(name) for name in names}.

How do I filter a dictionary by value?

Loop over .items() and add if: {k: v for k, v in d.items() if v > 10}.

Can I sort a dictionary with a comprehension?

Yes: {k: d[k] for k in sorted(d)} builds a new dictionary in key order.

Spotted a mistake on this page? Tell us