Python Data Structures
Python Dictionary Comprehension
Dictionary comprehension lets you build a new dictionary from an iterable in a single, readable line, similar to list comprehension.
Basic Syntax
The general form is {key_expr: value_expr for item in iterable}. Python evaluates both expressions for every item and builds the resulting dictionary.
squares = {n: n * n for n in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}Filtering Entries
Add an if condition at the end to include only the entries that pass a test — useful for pulling a subset out of a larger dictionary.
scores = {"Aarav": 82, "Riya": 45, "Kabir": 91}
passed = {name: s for name, s in scores.items() if s >= 50}
print(passed) # {'Aarav': 82, 'Kabir': 91}Transforming Values
You are not limited to copying values as-is — apply any expression to build a new dictionary derived from an existing one.
marks = {"Aarav": 82, "Riya": 45}
percent = {name: mark / 100 * 100 for name, mark in marks.items()}
print(percent)Swapping Keys and Values
A classic one-liner: loop over items() and flip the position of the key and value expressions. This only works cleanly when the original values are unique and immutable (hashable).
capitals = {"India": "Delhi", "Japan": "Tokyo"}
reversed_dict = {city: country for country, city in capitals.items()}
print(reversed_dict) # {'Delhi': 'India', 'Tokyo': 'Japan'}Comprehension vs a for Loop
A dict comprehension replaces a for loop that builds a new dictionary key by key. Use it when the logic is a single simple expression; fall back to a full loop for anything more complex.
nums = [1, 2, 3]
# for loop
squares = {}
for n in nums:
squares[n] = n * n
# dict comprehension
squares = {n: n * n for n in nums}Wrap a long dict comprehension across multiple lines for readability — Python ignores whitespace inside brackets.
