Dictionary comprehension with condition helps you create a new dictionary by picking only the items you want from another dictionary or sequence.
Dictionary comprehension with condition in Python
Start learning this pattern below
Jump into concepts and practice - no test required
{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.
numbers = {'a': 1, 'b': 2, 'c': 3}
new_dict = {k: v for k, v in numbers.items() if v > 1}words = ['apple', 'banana', 'cherry'] lengths = {word: len(word) for word in words if len(word) > 5}
This program filters the fruits dictionary to keep only those with quantity greater than 3.
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)Remember, the condition comes after the for part in the comprehension.
You can use multiple conditions by combining them with and or or.
Dictionary comprehension with condition lets you build dictionaries by filtering items easily.
Use it to create smaller dictionaries from bigger ones based on rules.
Practice
What does the following dictionary comprehension do?{k: v for k, v in {'a': 1, 'b': 2, 'c': 3}.items() if v > 1}
Solution
Step 1: Understand the dictionary comprehension structure
The comprehension loops over each key-value pair in the original dictionary.Step 2: Apply the condition
Only pairs where the value is greater than 1 are included in the new dictionary.if v > 1Final Answer:
{'b': 2, 'c': 3} - keeps items with values greater than 1 -> Option CQuick Check:
Filter values > 1 = {'b': 2, 'c': 3} [OK]
- Ignoring the condition and including all items
- Confusing keys and values in the condition
- Using wrong comparison operator
Which of the following is the correct syntax for a dictionary comprehension with a condition?
?Solution
Step 1: Recall dictionary comprehension syntax
The correct syntax is{key: value for key, value in iterable if condition}.Step 2: Identify the correct option
{k: v for k, v in d.items() if v % 2 == 0} matches the correct syntax withifafter the loop. Others use invalid keywords or wrong order.Final Answer:
{k: v for k, v in d.items() if v % 2 == 0} -> Option AQuick Check:
Correct syntax uses 'if' after for loop [OK]
- Placing 'if' before the for loop
- Using 'where' or 'when' instead of 'if'
- Incorrect order of clauses
What is the output of this code?
nums = {'x': 10, 'y': 5, 'z': 0}
filtered = {k: v for k, v in nums.items() if v}
print(filtered)Solution
Step 1: Understand the condition
This condition filters out values that are 'falsy' in Python, like 0, None, or empty.if vStep 2: Apply the condition to each item
Values 10 and 5 are truthy, so included; 0 is falsy, so excluded.Final Answer:
{'x': 10, 'y': 5} -> Option AQuick Check:
Falsy values excluded = {'x': 10, 'y': 5} [OK]
- Including zero as truthy
- Confusing keys and values
- Expecting all items to be included
Find the error in this dictionary comprehension:
data = {'a': 1, 'b': 2, 'c': 3}
result = {k: v for k, v in data.items() if v > 1 else 0}
print(result)Solution
Step 1: Check the use of else in comprehension condition
Dictionary comprehensions cannot have an else clause directly after the if condition.Step 2: Identify correct syntax
To use else, it must be inside a value expression with a ternary operator, not after if.Final Answer:
SyntaxError due to incorrect use of else in comprehension -> Option BQuick Check:
else must be inside value expression, not after if [OK]
- Placing else after if in comprehension
- Confusing ternary operator syntax
- Expecting else to filter keys
You have a dictionary of student scores:scores = {'Alice': 85, 'Bob': 42, 'Charlie': 73, 'David': 58}
Use dictionary comprehension with a condition to create a new dictionary passed containing only students who scored 60 or more, but store their scores as 'Pass' instead of the number.
Which code correctly does this?
Solution
Step 1: Understand the requirement
We want only students with scores 60 or more, and their values replaced by 'Pass'.Step 2: Check each option
{k: 'Pass' for k, v in scores.items() if v >= 60} filters withif v >= 60and sets value to 'Pass'. {k: 'Pass' if v >= 60 else 'Fail' for k, v in scores.items()} includes all students with ternary but no filtering. {k: v for k, v in scores.items() if v >= 60} keeps original scores. {k: 'Pass' for k, v in scores.items() if v > 60} excludes 60 exactly.Final Answer:
{k: 'Pass' for k, v in scores.items() if v >= 60} -> Option DQuick Check:
Filter and replace value with 'Pass' = {k: 'Pass' for k, v in scores.items() if v >= 60} [OK]
- Using else without filtering
- Not including scores equal to 60
- Keeping original scores instead of 'Pass'
