0
0
Pythonprogramming~20 mins

Why dictionary comprehension is used in Python - Challenge Your Understanding

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 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)
A{0: 0, 2: 4, 4: 16}
BSyntaxError
C{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
D{1: 1, 3: 9}
Attempts:
2 left
๐Ÿ’ก Hint
Look at the condition after the for loop inside the comprehension.
๐Ÿง  Conceptual
intermediate
1:30remaining
Why use dictionary comprehension instead of a loop?
Why is dictionary comprehension preferred over a traditional for-loop when creating dictionaries?
AIt always runs faster than any for-loop.
BIt is shorter and easier to read, making code cleaner.
CIt can only create dictionaries with string keys.
DIt does not allow conditions inside the comprehension.
Attempts:
2 left
๐Ÿ’ก Hint
Think about code length and readability.
โ“ Predict Output
advanced
2: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)
A{0: {0: 0, 1: 0, 2: 0}, 1: {0: 0, 1: 1, 2: 2}}
B{0: {0: 0, 1: 1, 2: 2}, 1: {0: 0, 1: 1, 2: 2}}
C{0: {0: 0, 1: 0, 2: 0}, 1: {0: 1, 1: 1, 2: 1}}
DTypeError
Attempts:
2 left
๐Ÿ’ก Hint
Look carefully at how i and j are multiplied inside the inner comprehension.
๐Ÿ”ง Debug
advanced
2: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)
ATypeError
BNo error, prints {3: 6, 4: 8}
CKeyError
DSyntaxError
Attempts:
2 left
๐Ÿ’ก Hint
Check the syntax of the comprehension carefully.
๐Ÿš€ Application
expert
3: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'
A{char: len(char) for char in text}
B{char: text.index(char) for char in text}
C{char: text.count(char) for char in text}
D{char: char*2 for char in text}
Attempts:
2 left
๐Ÿ’ก Hint
Think about how to count occurrences of each character.