If you love list comprehensions in Python, you're going to love dictionary comprehensions too. They're concise, expressive, and often much faster than traditional for-loops.
๐ What Is a Dictionary Comprehension?
A dictionary comprehension is a concise way to create dictionaries using an expression inside curly braces.
{key_expr: value_expr for item in iterable}
โ
Basic Example
Letโs create a dictionary where keys are numbers and values are their squares:
squares = {x: x**2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
๐ Reversing a Dictionary
original = {'a': 1, 'b': 2, 'c': 3}
reversed_dict = {v: k for k, v in original.items()}
print(reversed_dict) # {1: 'a', 2: 'b', 3: 'c'}
๐งผ Filtering with Conditions
Only include even keys:
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
๐ฆ Nested Dictionary Comprehensions
Creating a grid (2D dict):
grid = {(x, y): x*y for x in range(3) for y in range(3)}
๐ก Use Case: Rename JSON Keys
api_data = {'user_id': 1, 'user_name': 'alice'}
mapped = {k.replace('user_', ''): v for k, v in api_data.items()}
# {'id': 1, 'name': 'alice'}
โฑ๏ธ Why Use Them?
- Cleaner and more expressive
- Often faster than loops
- Ideal for transformations, filters, or small data manipulations
๐งช Pro Tip
- Use dictionary comprehensions when:
- Youโre transforming or filtering a dictionary
- Youโre building one from another iterable
- You want to keep your code elegant and Pythonic
Follow for more Python deep dives! ๐โก
Top comments (0)