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)