Bird
Raised Fist0
Pythonprogramming~20 mins

Dictionary comprehension with condition in Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
๐ŸŽ–๏ธ
Dictionary Comprehension Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
Output of dictionary comprehension with a simple condition
What is the output of this Python code?
Python
result = {x: x**2 for x in range(5) if x % 2 == 0}
print(result)
A{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
B{1: 1, 3: 9}
C{0: 0, 2: 4, 4: 16}
D{}
Attempts:
2 left
๐Ÿ’ก Hint
Remember, the condition filters keys where x is even.
โ“ Predict Output
intermediate
2:00remaining
Dictionary comprehension with else in value expression
What does this code print?
Python
result = {x: ('even' if x % 2 == 0 else 'odd') for x in range(3)}
print(result)
A{0: 'even', 1: 'odd', 2: 'even'}
B{0: 'odd', 1: 'even', 2: 'odd'}
C{0: 'even', 2: 'even'}
D{1: 'odd'}
Attempts:
2 left
๐Ÿ’ก Hint
The value uses a conditional expression to label even or odd.
โ“ Predict Output
advanced
2:30remaining
Output of nested dictionary comprehension with condition
What is the output of this code?
Python
result = {x: {y: x*y for y in range(3) if y != x} for x in range(3)}
print(result)
A{0: {}, 1: {}, 2: {}}
B{0: {1: 1, 2: 2}, 1: {0: 0, 2: 2}, 2: {0: 0, 1: 1}}
C{0: {0: 0, 1: 0, 2: 0}, 1: {0: 0, 1: 1, 2: 2}, 2: {0: 0, 1: 2, 2: 4}}
D{0: {1: 0, 2: 0}, 1: {0: 0, 2: 2}, 2: {0: 0, 1: 2}}
Attempts:
2 left
๐Ÿ’ก Hint
Inner comprehension excludes y equal to x.
โ“ Predict Output
advanced
2:30remaining
Dictionary comprehension with complex condition and filtering
What will be printed by this code?
Python
data = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
result = {k: v for k, v in data.items() if v % 2 == 0 and k != 'd'}
print(result)
A{'a': 1, 'c': 3}
B{'b': 2}
C{'b': 2, 'd': 4}
D{}
Attempts:
2 left
๐Ÿ’ก Hint
Filter keys with even values but exclude key 'd'.
๐Ÿง  Conceptual
expert
3:00remaining
Count of items in dictionary comprehension with multiple conditions
How many items are in the dictionary created by this comprehension? {num: num**3 for num in range(10) if num % 2 == 1 if num > 5}
A2
B5
C4
D3
Attempts:
2 left
๐Ÿ’ก Hint
Count numbers from 0 to 9 that are odd and greater than 5.

Practice

(1/5)
1.

What does the following dictionary comprehension do?
{k: v for k, v in {'a': 1, 'b': 2, 'c': 3}.items() if v > 1}

easy
A. {'a': 1, 'b': 2, 'c': 3} - keeps all items
B. {'a': 1} - keeps items with values equal to 1
C. {'b': 2, 'c': 3} - keeps items with values greater than 1
D. {} - removes all items

Solution

  1. Step 1: Understand the dictionary comprehension structure

    The comprehension loops over each key-value pair in the original dictionary.
  2. Step 2: Apply the condition if v > 1

    Only pairs where the value is greater than 1 are included in the new dictionary.
  3. Final Answer:

    {'b': 2, 'c': 3} - keeps items with values greater than 1 -> Option C
  4. Quick Check:

    Filter values > 1 = {'b': 2, 'c': 3} [OK]
Hint: Look for the condition after the for loop to filter items [OK]
Common Mistakes:
  • Ignoring the condition and including all items
  • Confusing keys and values in the condition
  • Using wrong comparison operator
2.

Which of the following is the correct syntax for a dictionary comprehension with a condition?

?
easy
A. {k: v for k, v in d.items() if v % 2 == 0}
B. {k: v if v % 2 == 0 for k, v in d.items()}
C. {k: v for k, v in d.items() where v % 2 == 0}
D. {k: v for k, v in d.items() when v % 2 == 0}

Solution

  1. Step 1: Recall dictionary comprehension syntax

    The correct syntax is {key: value for key, value in iterable if condition}.
  2. Step 2: Identify the correct option

    {k: v for k, v in d.items() if v % 2 == 0} matches the correct syntax with if after the loop. Others use invalid keywords or wrong order.
  3. Final Answer:

    {k: v for k, v in d.items() if v % 2 == 0} -> Option A
  4. Quick Check:

    Correct syntax uses 'if' after for loop [OK]
Hint: Remember: condition goes after the for clause in comprehension [OK]
Common Mistakes:
  • Placing 'if' before the for loop
  • Using 'where' or 'when' instead of 'if'
  • Incorrect order of clauses
3.

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)

medium
A. {'x': 10, 'y': 5}
B. {}
C. {'z': 0}
D. {'x': 10, 'y': 5, 'z': 0}

Solution

  1. Step 1: Understand the condition if v

    This condition filters out values that are 'falsy' in Python, like 0, None, or empty.
  2. Step 2: Apply the condition to each item

    Values 10 and 5 are truthy, so included; 0 is falsy, so excluded.
  3. Final Answer:

    {'x': 10, 'y': 5} -> Option A
  4. Quick Check:

    Falsy values excluded = {'x': 10, 'y': 5} [OK]
Hint: Falsy values like 0 are skipped when condition is just 'if v' [OK]
Common Mistakes:
  • Including zero as truthy
  • Confusing keys and values
  • Expecting all items to be included
4.

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)

medium
A. No error, outputs {'b': 2, 'c': 3}
B. SyntaxError due to incorrect use of else in comprehension
C. Outputs {'a': 0, 'b': 2, 'c': 3}
D. KeyError because of else clause

Solution

  1. Step 1: Check the use of else in comprehension condition

    Dictionary comprehensions cannot have an else clause directly after the if condition.
  2. Step 2: Identify correct syntax

    To use else, it must be inside a value expression with a ternary operator, not after if.
  3. Final Answer:

    SyntaxError due to incorrect use of else in comprehension -> Option B
  4. Quick Check:

    else must be inside value expression, not after if [OK]
Hint: Use ternary inside value, not else after if in comprehension [OK]
Common Mistakes:
  • Placing else after if in comprehension
  • Confusing ternary operator syntax
  • Expecting else to filter keys
5.

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?

hard
A. {k: 'Pass' for k, v in scores.items() if v > 60}
B. {k: 'Pass' if v >= 60 else 'Fail' for k, v in scores.items()}
C. {k: v for k, v in scores.items() if v >= 60}
D. {k: 'Pass' for k, v in scores.items() if v >= 60}

Solution

  1. Step 1: Understand the requirement

    We want only students with scores 60 or more, and their values replaced by 'Pass'.
  2. Step 2: Check each option

    {k: 'Pass' for k, v in scores.items() if v >= 60} filters with if v >= 60 and 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.
  3. Final Answer:

    {k: 'Pass' for k, v in scores.items() if v >= 60} -> Option D
  4. Quick Check:

    Filter and replace value with 'Pass' = {k: 'Pass' for k, v in scores.items() if v >= 60} [OK]
Hint: Filter with if, set value directly to 'Pass' in comprehension [OK]
Common Mistakes:
  • Using else without filtering
  • Not including scores equal to 60
  • Keeping original scores instead of 'Pass'