Dictionary Comprehensions
Dict comprehensions create dictionaries in one line. Syntax: {key: value for item in iterable if condition}.
10 min•By Priygop Team•Updated 2026
Dict Comprehensions
Dict Comprehensions
# Basic dict comprehension
squares = {x: x**2 for x in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# With condition
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
print(even_squares)
# From two lists
keys = ["name", "age", "city"]
values = ["Alice", 25, "Mumbai"]
person = dict(zip(keys, values))
print(person)
# Swap keys and values
original = {"a": 1, "b": 2, "c": 3}
swapped = {v: k for k, v in original.items()}
print(swapped) # {1: 'a', 2: 'b', 3: 'c'}
# Practical: word frequency
sentence = "the cat sat on the mat"
word_count = {word: sentence.split().count(word)
for word in set(sentence.split())}
print(word_count)Tip
Tip
Use dict(zip(keys, values)) to create dicts from two lists. Swap keys/values with {v:k for k,v in d.items()}.
Diagram
Loading diagram…
List comp for most cases. Generator for large data (lazy). Dict comp for transforming dicts. Readable > clever.
Common Mistake
Warning
Dict comprehension overwrites duplicate keys silently. The last value wins. Ensure keys are unique.
Practice Task
Note
(1) Create a squares dict {1:1, 2:4, ...10:100}. (2) Swap keys and values. (3) Filter a dict to keep only positive values.