DEV Community

Mohammad Nadeem
Mohammad Nadeem

Posted on

Dictionary Comprehensions in Python: Powerful, Elegant, and Fast

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}
Enter fullscreen mode Exit fullscreen mode

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}

Enter fullscreen mode Exit fullscreen mode

🔄 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'}
Enter fullscreen mode Exit fullscreen mode

🧼 Filtering with Conditions
Only include even keys:

even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
Enter fullscreen mode Exit fullscreen mode

📦 Nested Dictionary Comprehensions
Creating a grid (2D dict):

grid = {(x, y): x*y for x in range(3) for y in range(3)}
Enter fullscreen mode Exit fullscreen mode

💡 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'}
Enter fullscreen mode Exit fullscreen mode

⏱️ 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)