← Back to Python Course | Chapter 6: Data Structures | Lesson 9 of 12

Python Dict Comprehension

A dictionary comprehension builds a whole labeled collection in one line, like stamping out name tags for every guest at once. It is a compact way to make key-value pairs.
Syntax
python
new_dict = {key_expr: value_expr for item in iterable if condition}

Basic Dict Comprehension

Dictionary comprehensions build a new dict in one expression using {key_expr: value_expr for item in iterable}, which is the dict equivalent of a list comprehension and is typically faster and more readable than looping with an empty dict and repeated assignment.

Example: Basic Dict Comprehension

python
nums = [1, 2, 3]
squares = {n: n * n for n in nums}  # key is n, value is its square
print(squares)

Filtering with If-Conditions

Adding 'if condition' at the end filters which source items get turned into entries -- {k: v for k, v in pairs if v > 0} keeps only the pairs whose value is positive, discarding the rest entirely rather than transforming them.

Example: Filtering with If-Conditions

python
pairs = {"a": 1, "b": -2, "c": 3}
positive = {k: v for k, v in pairs.items() if v > 0}  # if filters out non-positive values
print(positive)

Transforming Keys and Values

You can compute both the key and the value from the same source item, letting you reshape data as you go -- for example {name.lower(): len(name) for name in names} both normalizes the key and derives a new value in a single pass.

Example: Transforming Keys and Values

python
names = ["Alice", "Bob"]
lengths = {name.lower(): len(name) for name in names}  # key is lowercased, value is the length
print(lengths)

Creating Dict from Two Lists

zip() pairs up two same-length lists element by element, and wrapping that in a comprehension -- {k: v for k, v in zip(keys, values)} -- turns two parallel lists into a single dictionary without a manual loop.

Example: Creating Dict from Two Lists

python
keys = ["a", "b", "c"]
values = [1, 2, 3]
combined = {k: v for k, v in zip(keys, values)}  # zip pairs the two lists element by element
print(combined)

Comprehension with If-Else Conditions

Placing a ternary if-else before the for clause lets every key get a value based on a condition rather than being excluded -- {k: pass if v >= 50 else fail for k, v in scores.items()} keeps every key while varying its mapped value.

Example: Comprehension with If-Else Conditions

python
scores = {"Alex": 80, "Sam": 40}
results = {k: "pass" if v >= 50 else "fail" for k, v in scores.items()}  # every key is kept, value depends on the condition
print(results)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting the colon, as in {k v for k, v in pairs}, which is a SyntaxError; a dict comprehension needs key: value.
  2. Building duplicate keys and expecting all values to be kept, when later entries overwrite earlier ones with the same key.
  3. Writing {} around a plain expression such as {x for x in items}, which creates a set, not a dictionary.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.