Dictionary Comprehension in Python

What is Dictionary Comprehension? A dictionary comprehension is a concise way to create dictionaries in Python. It’s similar to list comprehension, but instead of generating a list, it creates a dictionary ({key: value} pairs).

Syntax of Dictionary Comprehension {key_expression: value_expression for item in iterable if condition}

Explanation:

Example: Squares of numbers.

Python

# Create a dictionary of numbers and their squares
squares = {x: x**2 for x in range(5)}

print(squares)

Output {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

This code is equivalent to

Python

squares = {}
for x in range(5):
    squares[x] = x*x
print(squares)

Dictionary Comprehension with Condition

Python

# Keep only even numbers
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}

print(even_squares)

Output {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}