0
0
Pythonprogramming~5 mins

Dictionary comprehension with condition in Python

Choose your learning style9 modes available
Introduction

Dictionary comprehension with condition helps you create a new dictionary by picking only the items you want from another dictionary or sequence.

You want to filter a dictionary to keep only certain keys or values.
You need to create a smaller dictionary from a bigger one based on some rule.
You want to quickly transform data but only include items that meet a condition.
Syntax
Python
{key_expression: value_expression for item in iterable if condition}

The if condition part filters items before adding them to the new dictionary.

You can use any expression for keys and values, not just simple variables.

Examples
This keeps only items where the value is greater than 1.
Python
numbers = {'a': 1, 'b': 2, 'c': 3}
new_dict = {k: v for k, v in numbers.items() if v > 1}
This creates a dictionary of words with their lengths, but only for words longer than 5 letters.
Python
words = ['apple', 'banana', 'cherry']
lengths = {word: len(word) for word in words if len(word) > 5}
Sample Program

This program filters the fruits dictionary to keep only those with quantity greater than 3.

Python
fruits = {'apple': 5, 'banana': 3, 'cherry': 7, 'date': 2}
# Keep fruits with quantity more than 3
filtered = {fruit: qty for fruit, qty in fruits.items() if qty > 3}
print(filtered)
OutputSuccess
Important Notes

Remember, the condition comes after the for part in the comprehension.

You can use multiple conditions by combining them with and or or.

Summary

Dictionary comprehension with condition lets you build dictionaries by filtering items easily.

Use it to create smaller dictionaries from bigger ones based on rules.