0
0
Pythonprogramming~20 mins

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

Choose your learning style9 modes available
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.