Dictionary Comprehensions| Dataplexa

Dictionary Comprehensions in Python

Dictionary Comprehensions allow you to create dictionaries in a clean, fast, and readable way — just like list comprehensions but for key–value pairs. This feature is extremely useful for transforming data, filtering information, and building structured outputs in a single efficient line.

By learning dictionary comprehensions, you take another major step toward writing professional-level Python code. They are widely used in data science, automation, JSON processing, and application development.

What Is a Dictionary Comprehension?

A dictionary comprehension creates a dictionary by looping through an iterable and forming key–value pairs dynamically.

Basic Pattern:

{key_expression : value_expression for item in iterable}

Just like list comprehensions, but here you define both the key and the value.

Why Use Dictionary Comprehensions?

They offer several advantages:

  • Cleaner syntax than traditional loops
  • Fast performance
  • Better readability
  • Useful for transforming lists into dictionaries
  • Helpful for filtering or mapping data

Example 1: Create a Dictionary of Number Squares

Traditional loop method:

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

Now using dictionary comprehension:

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

The result: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Example 2: Convert List of Words Into a Dictionary of Word Lengths

This is useful when analyzing text or preparing features for machine learning.

words = ["python", "code", "dataplexa"]
length_map = {word: len(word) for word in words}
print(length_map)

This gives each word as a key and its length as a value.

Dictionary Comprehension with Conditions

We can filter items while building the dictionary.

Pattern:

{key: value for item in iterable if condition}

Example 3: Keep Only Even Numbers

numbers = range(10)
even_map = {x: x * 2 for x in numbers if x % 2 == 0}
print(even_map)

This stores only even numbers and their doubles.

Using if–else Inside Dictionary Comprehension

You can apply conditions inside the value (or key) expression. This is perfect for classification tasks.

Pattern:

{key: (value_if_true if condition else value_if_false) for item in iterable}

Example 4: Label Numbers as "Even" or "Odd"

numbers = [1, 2, 3, 4, 5]
labels = {x: ("Even" if x % 2 == 0 else "Odd") for x in numbers}
print(labels)

Result: {1: 'Odd', 2: 'Even', 3: 'Odd', 4: 'Even', 5: 'Odd'}

Example 5: Swap Keys and Values

This technique is helpful when cleaning or restructuring data.

data = {"a": 1, "b": 2, "c": 3}
swapped = {value: key for key, value in data.items()}
print(swapped)

Example 6: Filter Dictionary Based on Value

Real use case: keeping only high scores, prices above a limit, or valid entries.

scores = {"ram": 45, "john": 82, "sita": 91, "raj": 55}
passed = {name: score for name, score in scores.items() if score >= 60}
print(passed)

Nested Dictionary Comprehensions

You can also create multi-level structured dictionaries using nested loops. This is used in grids, matrices, and structured JSON generation.

Example 7: Create a Table of Multiplications

table = {x: {y: x * y for y in range(1, 6)} for x in range(1, 6)}
print(table)

This generates a multiplication table for numbers 1 to 5.


Common Use Cases of Dictionary Comprehensions

  • Transforming lists into dictionaries
  • Filtering data
  • Processing JSON objects
  • Counting or grouping values
  • Cleaning messy datasets
  • Reversing keys and values

📝 Practice Exercises


Exercise 1

Create a dictionary where keys are numbers 1 to 5 and values are their cubes.

Exercise 2

Given names = ["ram", "sita", "hari"], create a dictionary with names as keys and their uppercase versions as values.

Exercise 3

From dictionary {"a": 10, "b": 3, "c": 25, "d": 12}, create a new dictionary keeping only values greater than 10.

Exercise 4

Convert a list of marks into pass/fail dictionary: [30, 75, 55, 90, 42] Pass = score ≥ 50


✅ Practice Answers


Answer 1

cubes = {x: x**3 for x in range(1, 6)}
print(cubes)

Answer 2

names = ["ram", "sita", "hari"]
result = {name: name.upper() for name in names}
print(result)

Answer 3

data = {"a": 10, "b": 3, "c": 25, "d": 12}
filtered = {k: v for k, v in data.items() if v > 10}
print(filtered)

Answer 4

marks = [30, 75, 55, 90, 42]
status = {m: ("Pass" if m >= 50 else "Fail") for m in marks}
print(status)