Introduction: Python Dictionary Comprehension
Python dictionary comprehension gives you a quick and clean way to create dictionaries without writing long loops. Instead of using multiple lines with loops and assignments, it allows key-value pairs to be generated in a cleaner and more compact format.
It works in a similar way to list comprehension, but instead of producing a list, it creates a dictionary.
This is useful when values need to be generated dynamically, filtered, transformed, or created from another iterable.
Purpose of Python Dictionary Comprehension:
- Create dictionaries in a shorter and cleaner way
- Reduce the need for long loops and repeated assignments
- Generate key-value pairs dynamically
- Filter or transform dictionary data easily
- Improve code readability for simple dictionary operations
Now that the idea is clear, the next step is to see how dictionary comprehension is written in Python before moving on to examples.
Tip: Dictionary comprehension becomes easier once the fundamentals are clear. Review our Python Dictionary syntax and concepts guide.
Syntax, Examples and Use Cases: Python Dictionary Comprehension
The basic syntax of dictionary comprehension is shown below:
{key: value for item in iterable}
You can also add a condition to filter items:
{key: value for item in iterable if condition}
Components of Dictionary Comprehension
| Element | Description |
|---|---|
| key | The key that will be stored in the dictionary |
| value | The value associated with the key |
| item | The current element from the iterable |
| iterable | The sequence being looped through |
| condition | Optional filter to include only specific items |
Return Value
Dictionary comprehension returns a new dictionary containing the generated key-value pairs.
Examples of Python Dictionary Comprehension
The following examples show how dictionary comprehension works in Python with simple and practical use cases.
Example 1: Create a Dictionary of Squares
This example shows how dictionary comprehension can be used to generate key-value pairs where each number is paired with its square.
squares = {x: x * x for x in range(1, 6)}
print(squares)
# Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Explanation: The loop runs through numbers from 1 to 5. Each number is used as a key, and its square is stored as the corresponding value in the dictionary.
Example 2: Create a Dictionary with Even Numbers Only
Conditions can be added to include only specific items in the final dictionary.
even_squares = {x: x * x for x in range(1, 11) if x % 2 == 0}
print(even_squares)
# Output:
{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
Explanation: Only even numbers are included because of the condition x % 2 == 0. Odd numbers are skipped.
Example 3: Convert Values to Uppercase
Dictionary comprehension can also be used to transform existing dictionary values.
students = {"alice": "pass", "bob": "fail"}
result = {name: status.upper() for name, status in students.items()}
print(result)
# Output:
{'alice': 'PASS', 'bob': 'FAIL'}
Explanation: The code loops through each key-value pair in the original dictionary. The values are converted to uppercase before being stored in the new dictionary.
Example 4: Swap Keys and Values
Sometimes keys need to become values and values need to become keys.
data = {"a": 1, "b": 2, "c": 3}
reversed_data = {value: key for key, value in data.items()}
print(reversed_data)
# Output:
{1: 'a', 2: 'b', 3: 'c'}
Explanation: The original dictionary is reversed by placing the value first and the key second. This creates a new dictionary with swapped positions.
Example 5: Create a Dictionary from Two Lists
Dictionary comprehension can combine values from different lists into one dictionary.
keys = ["name", "age", "city"]
values = ["Alice", 25, "London"]
result = {keys[i]: values[i] for i in range(len(keys))}
print(result)
# Output:
{'name': 'Alice', 'age': 25, 'city': 'London'}
Explanation: The loop uses the index position to match each key with its related value. This is useful when keys and values are stored separately.
Example 6: Filter a Dictionary Based on Values
Dictionary comprehension can also create a smaller dictionary by filtering out unwanted items.
marks = {"Alice": 85, "Bob": 45, "Charlie": 72}
passed_students = {name: mark for name, mark in marks.items() if mark >= 50}
print(passed_students)
# Output:
{'Alice': 85, 'Charlie': 72}
Explanation: The condition keeps only students with marks greater than or equal to 50. Bob is removed because his mark is below 50.
Use Cases: Dictionary Comprehension
Here are some common real-world use cases where Python dictionary comprehension is widely used:
- Creating dictionaries from lists or ranges in a single line
- Generating values like squares, cubes, or other calculations
- Filtering data based on conditions (e.g., even numbers, valid values)
- Transforming values such as changing case or format
- Swapping keys and values in a dictionary
- Converting or cleaning data in APIs and web applications
Key Takeaways: Dictionary Comprehension
Before wrapping up, here are the key points to remember about Python dictionary comprehension:
- Dictionary comprehension provides a short and clean way to create dictionaries.
- It reduces the need for long loops and repeated assignments.
- You can generate key-value pairs dynamically in a single line.
- It supports conditions for filtering and transforming data.
- It is commonly used for data cleaning, transformation, and quick dictionary creation.