Dictionary Comprehension in Python

To make a dictionary from a list of values, each item needs a key and a value. A dictionary comprehension builds those key-value pairs from an iterable, with optional conditions to filter items or choose a value.

I’ll show how to build a dictionary comprehension and use conditions to filter entries or choose their values.

TL;DR

A dictionary comprehension creates key-value pairs from an iterable in one expression, with optional filtering or transformation.

  • Use the form {key: value for item in iterable} to make a new dictionary.
  • Add a trailing if to skip items, or place an if/else expression in the value to choose a value for every item.
  • Use dict(zip(keys, values)) when pairing two ready-made sequences without changing their values.

What Is a Dictionary Comprehension in Python?

A dictionary comprehension builds a new dictionary by evaluating a key expression and a value expression for each item that passes its conditions. The iterable supplies those items, such as values from a list or key-value pairs from another dictionary.

A dictionary comprehension uses curly braces to put a key expression before the colon and a value expression after it, followed by its for clause. I’ll begin with a single input and show how it determines the key-value pair. A list comprehension uses square brackets and produces a list rather than a mapping.

PartWhat it supplies
key expressionThe key for the new dictionary entry. The result must be hashable.
value expressionThe value paired with that key. It can transform the current item.
for clauseThe loop variable and the iterable that provides each item.
optional ifA filter that leaves out items when its condition is false.

For a source dictionary, dict.items() provides each key and value together. The comprehension can keep the original key while changing the value, or use the pair to decide whether an entry belongs in the result. The AskPython dictionary tutorial covers the mapping operations used here.

How to Build a Dictionary Comprehension Step by Step

Start with the input data, choose what each output key and value should be, then add a condition only when some items must be skipped. The examples below use a runnable file for each common task so the printed result can be checked against the expression.

Step 1: Map Each Input Item to a Key and Value

Use each number as a key and its square as the value. I ran python3 dictionary_build_demo.py, and the resulting mapping is shown below.

numbers = [1, 2, 3, 4, 5]
squares = {number: number**2 for number in numbers}
print(squares)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Python dictionary comprehension mapping integers to their squares
The printed dictionary maps each input number to its square.

The expression before the for clause calculates one pair on each pass. Notice that the keys stay as input numbers while only the values are squared.

Step 2: Filter Items or Choose a Value

A trailing if filters items out of the result. An if/else expression inside the value instead keeps each item and chooses which value to store. I ran python3 dictionary_conditions_demo.py and checked both results below.

numbers = [1, 2, 3, 4, 5]
even_squares = {
    number: number**2
    for number in numbers
    if number % 2 == 0
}
labels = {
    number: "even" if number % 2 == 0 else "odd"
    for number in numbers
}
print("filtered =", even_squares)
print("conditional values =", labels)
filtered = {2: 4, 4: 16}
conditional values = {1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd'}
Python dictionary comprehension filtering even squares and assigning parity labels
The first result omits odd numbers. The second assigns a label to every number.

The first result has two entries because the filter rejects the other numbers. The second has five because its conditional expression selects a value for each item. Keep the filter after the iterable, so an if/else expression stays with the key or value.

Step 3: Transform Values from an Existing Dictionary

Use dict.items() when a result depends on both halves of an existing entry. I ran python3 dictionary_transform_demo.py. The terminal shows converted measurements beside a filtered copy.

prices_cm = {"pen": 40, "book": 120, "desk": 0}
prices_m = {
    item: centimeters / 100
    for item, centimeters in prices_cm.items()
}
available = {
    item: centimeters
    for item, centimeters in prices_cm.items()
    if centimeters > 0
}
print("meters =", prices_m)
print("nonzero =", available)
meters = {'pen': 0.4, 'book': 1.2, 'desk': 0.0}
nonzero = {'pen': 40, 'book': 120}
Python dictionary comprehension converting centimeter values and filtering entries
The output shows a value conversion and a filtered copy of the source mapping.

The first comprehension converts every measurement. Its partner excludes zero-valued entries. The dictionary guide covers more mapping operations.

Step 4: Pair Two Iterables When Their Values Are Ready

When you already have matching keys and values, dict(zip(keys, values)) expresses the pairing directly. I ran python3 dictionary_zip_demo.py to check the paired lists and a repeated key.

labels = ["name", "language"]
values = ["Ada", "Python"]
profile = dict(zip(labels, values))

pairs = [("a", 1), ("a", 2)]
last_value = {key: value for key, value in pairs}
print("paired =", profile)
print("duplicate key =", last_value)
paired = {'name': 'Ada', 'language': 'Python'}
duplicate key = {'a': 2}
Python dictionary creation from paired lists and repeated keys
The output pairs two lists and keeps the later value for a repeated key.

The Python tutorial documents dict(zip(…)) as a direct way to pair sequences. Use a comprehension instead when you need to calculate a key or value, filter an item, or apply a transformation during construction. The AskPython list-comprehension guide explains the related syntax for building lists.

Common Edge Cases in Python Dictionary Comprehensions

A dictionary comprehension can produce an unexpected mapping when generated keys repeat, a key is unhashable, or paired iterables have different lengths. The table below shows what happens in each case and when an explicit loop is clearer to review.

CaseWhat happensPractical choice
Repeated generated keyThe later value replaces the earlier value for that key.Group values into lists first if every original value must be retained.
Unhashable key, such as a listDictionary creation raises TypeError because keys must be hashable.Convert the key to a hashable representation, such as a tuple, when that preserves its meaning.
Unequal inputs passed to zip()Pairing stops when the shorter iterable is exhausted.Check lengths first or use strict=True in Python 3.10+ when unequal lengths should raise an error.
Nested logic with several conditionsThe result may be correct but harder to review.Use named intermediate values or an explicit loop to make each decision visible.

The Python dict documentation explains key rules and replacement values. The zip documentation describes strict pairing and its default stopping point.

A comprehension cannot preserve two values under one identical key because a dictionary has one value for each key. If the result needs both values, build a grouped structure instead of relying on which duplicate appears last.

Conclusion: Match Each Input to a Key and Value

Choose syntax that makes the output’s rules apparent to the next reader. For the underlying rules, see the Python comprehension syntax and AskPython’s guides to dictionaries and list comprehensions.

FAQ

These quick answers cover syntax choices that readers often mix up.

What is the syntax for a dictionary comprehension in Python?

Write a key expression and value expression before the for clause inside braces: {key: value for item in iterable}. Add a trailing if clause to filter items.

Can a dictionary comprehension include an if/else expression?

Yes. Put the conditional expression in the key or value expression, before the for clause. A trailing if clause filters items instead.

What happens when a dictionary comprehension creates the same key twice?

The later value replaces the earlier value for that key. Use a grouped value, such as a list, when you need to retain every value.

How do you create a dictionary from two lists in Python?

Use dict(zip(keys, values)) when corresponding items are already the values you want. By default, zip stops when the shorter iterable ends.

Vijaykrishna Ram
Vijaykrishna Ram
Articles: 99