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 condition
What is the output of this Python code using dictionary comprehension with a condition?
Python
result = {x: x*x for x in range(5) if x % 2 == 0}
print(result)Attempts:
2 left
๐ก Hint
Look at the condition after the for loop inside the comprehension.
โ Incorrect
The comprehension creates key-value pairs for x and x squared only when x is even (x % 2 == 0). So keys 0, 2, and 4 are included.
๐ง Conceptual
intermediate1:30remaining
Why use dictionary comprehension instead of a loop?
Why is dictionary comprehension preferred over a traditional for-loop when creating dictionaries?
Attempts:
2 left
๐ก Hint
Think about code length and readability.
โ Incorrect
Dictionary comprehension lets you write dictionary creation in one line, making code shorter and easier to understand.
โ Predict Output
advanced2:30remaining
Output of nested dictionary comprehension
What is the output of this nested dictionary comprehension code?
Python
matrix = {i: {j: i*j for j in range(3)} for i in range(2)}
print(matrix)Attempts:
2 left
๐ก Hint
Look carefully at how i and j are multiplied inside the inner comprehension.
โ Incorrect
The outer loop runs for i in 0 and 1. For each i, the inner loop creates a dictionary with keys 0 to 2 and values i*j.
๐ง Debug
advanced2:00remaining
Identify the error in dictionary comprehension
What error does this code raise?
Python
result = {x: x*2 if x > 2 for x in range(5)}
print(result)Attempts:
2 left
๐ก Hint
Check the syntax of the comprehension carefully.
โ Incorrect
The syntax is invalid because the if condition is used incorrectly inside the comprehension without else.
๐ Application
expert3:00remaining
Count character frequency using dictionary comprehension
Which option correctly creates a dictionary counting each character's frequency in the string 'banana'?
Python
text = 'banana'Attempts:
2 left
๐ก Hint
Think about how to count occurrences of each character.
โ Incorrect
Option C counts how many times each character appears using text.count(char). Others do not count frequency.