Advertisement
📦 Data Structures

Python Dictionary Comprehensions – Concise Dict Creation

Dictionary comprehensions create dictionaries in a single, readable expression — similar to list comprehensions but producing key-value pairs. They are faster than equivalent for-loop dictionary creation and are considered the most Pythonic way to build dictionaries from existing data.

⏱️ 18 min read 🎯 Intermediate 📅 Updated 2026

Basic Dictionary Comprehension Syntax

The syntax is: {key_expression: value_expression for item in iterable}.

Python
# Basic dict comprehension
squares = {x: x**2 for x in range(1, 6)}
print(squares)

# Equivalent for-loop (more verbose):
squares_loop = {}
for x in range(1, 6):
    squares_loop[x] = x**2
▶ Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Dict Comprehension with Filtering

Add an if condition to filter which items get included.

Python
numbers = range(1, 11)

# Only even numbers
even_squares = {x: x**2 for x in numbers if x % 2 == 0}
print(even_squares)
▶ Output
{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
Advertisement

Transforming an Existing Dict

Apply transformations to keys or values of an existing dictionary.

Python
prices = {"apple": 1.50, "banana": 0.75, "cherry": 2.00}

# Apply 20% discount to all prices
discounted = {item: round(price * 0.8, 2) for item, price in prices.items()}
print(discounted)

# Make all keys uppercase
upper_prices = {k.upper(): v for k, v in prices.items()}
print(upper_prices)
▶ Output
{'apple': 1.2, 'banana': 0.6, 'cherry': 1.6} {'APPLE': 1.5, 'BANANA': 0.75, 'CHERRY': 2.0}

Inverting a Dictionary

Swap keys and values. Only works if values are unique and hashable.

Python
original = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in original.items()}
print(inverted)
▶ Output
{1: 'a', 2: 'b', 3: 'c'}

Building Dict from Two Lists

Use zip() to pair two lists into a dictionary.

Python
keys = ["name", "age", "city"]
values = ["Alice", 30, "London"]

result = {k: v for k, v in zip(keys, values)}
print(result)

# Or even simpler:
result2 = dict(zip(keys, values))
print(result2)
▶ Output
{'name': 'Alice', 'age': 30, 'city': 'London'} {'name': 'Alice', 'age': 30, 'city': 'London'}

Dict Comprehensions: Build Maps in One Expression

A dict comprehension creates a dictionary from an iterable in a single readable line — the same idea as a list comprehension, but producing key: value pairs.

nums = [1, 2, 3, 4]
squares = {n: n*n for n in nums}          # {1: 1, 2: 4, 3: 9, 4: 16}

# filter while building
evens = {n: n*n for n in nums if n % 2 == 0}   # {2: 4, 4: 16}

# invert a dict (swap keys and values)
inverted = {v: k for k, v in original.items()}

# build from two lists
dict(zip(keys, values))                    # pairs them up
TaskComprehension
transform values{k: f(v) for k, v in d.items()}
filter keys{k: v for k, v in d.items() if cond}
invert{v: k for k, v in d.items()}

Two common uses: transforming an existing dict (apply a function to every value, or keep only some keys) and building a lookup table from data. Iterate with .items() to get key and value together. Gotchas: keys must be unique — if your expression produces the same key twice, the later value silently wins. And keys must be hashable, so inverting a dict only works if the values were hashable (no lists as values → keys). For simple key/value pairing from two sequences, dict(zip(keys, values)) is even shorter.

🏋️ Practical Exercise

Practice building dicts concisely:

  1. Create a dict mapping numbers 1–5 to their squares with a comprehension.
  2. Filter an existing prices dict to keep only items costing more than $10.
  3. Build a dict from two lists (names and scores) using zip().
  4. Invert a dict so its values become keys and vice versa.

🔥 Challenge Exercise

Given a sentence, build a dictionary that counts how many times each word appears, using a dict comprehension over the unique words. Then create a second comprehension that keeps only the words appearing more than once, and a third that maps each word to its length. Bonus: normalize case and strip punctuation before counting.

📋 Summary

  • A dict comprehension builds a dictionary in one expression: {k: v for item in iterable}.
  • Add a filter with a trailing if: {k: v for ... if condition}.
  • Pair two lists into a dict with {k: v for k, v in zip(keys, values)}.
  • Invert a dict with {v: k for k, v in d.items()} (assuming values are unique).
  • They are usually more concise and slightly faster than an equivalent for loop.
  • Keep them readable — move complex logic into a loop or helper if a comprehension gets dense.

Interview Questions on Dictionary Comprehensions

  • What is a dictionary comprehension and what is its syntax?
  • How do you add a condition (filter) to a dict comprehension?
  • How do you build a dictionary from two lists?
  • How do you invert a dictionary using a comprehension?
  • What is the difference between a dict comprehension and a list comprehension?
  • Are dict comprehensions faster than building a dict in a loop?
  • Can you nest dict comprehensions?

FAQ

How is a dict comprehension different from a list comprehension? +

A list comprehension uses square brackets and produces a list of single values. A dict comprehension uses curly braces and a key: value expression, producing key–value pairs. Otherwise the looping and filtering syntax is identical.

Are dict comprehensions faster than a loop? +

Usually a little faster, because the work happens in optimized C internally and avoids repeated dict[key] = value calls. The bigger benefit is readability for simple transformations.

How do I invert a dictionary? +

Use {v: k for k, v in d.items()}. Be aware that if two keys share the same value, the inverted dict keeps only the last one, since dict keys must be unique.

Can I filter and transform at the same time? +

Yes. Put the transformation in the key: value part and the filter in a trailing if, e.g. {k: v*2 for k, v in d.items() if v > 0}.