Challenge - 5 Problems
Dictionary Comprehension Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2: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)Attempts:
2 left
๐ก Hint
Remember, the condition filters keys where x is even.
โ Incorrect
The comprehension includes only keys where x % 2 == 0, so only 0, 2, and 4 are included with their squares.
โ Predict Output
intermediate2: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)Attempts:
2 left
๐ก Hint
The value uses a conditional expression to label even or odd.
โ Incorrect
Each key from 0 to 2 is included. Values are 'even' if key is even, else 'odd'.
โ Predict Output
advanced2: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)Attempts:
2 left
๐ก Hint
Inner comprehension excludes y equal to x.
โ Incorrect
For each x, inner dict includes y from 0 to 2 except y == x, mapping y to x*y.
โ Predict Output
advanced2: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)Attempts:
2 left
๐ก Hint
Filter keys with even values but exclude key 'd'.
โ Incorrect
Only 'b' has an even value and key not equal to 'd', so only {'b': 2} remains.
๐ง Conceptual
expert3: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}
Attempts:
2 left
๐ก Hint
Count numbers from 0 to 9 that are odd and greater than 5.
โ Incorrect
Numbers 7 and 9 satisfy both conditions, so the dictionary has 2 items.