0
0
Pythonprogramming~20 mins

Basic dictionary comprehension 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 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}
DSyntaxError
Attempts:
2 left
๐Ÿ’ก Hint
Look at the condition after the for loop inside the comprehension.
โ“ Predict Output
intermediate
2:00remaining
Dictionary comprehension with ternary expression
What does this code print?
Python
result = {x: ('even' if x % 2 == 0 else 'odd') for x in range(4)}
print(result)
A{0: 'even', 1: 'odd', 2: 'even', 3: 'odd'}
B{0: 'odd', 1: 'even', 2: 'odd', 3: 'even'}
C{0: True, 1: False, 2: True, 3: False}
DTypeError
Attempts:
2 left
๐Ÿ’ก Hint
Check how the ternary operator assigns values based on even or odd keys.
โ“ Predict Output
advanced
2:30remaining
Output of nested dictionary comprehension
What is the output of this code?
Python
result = {x: {y: x*y for y in range(2)} for x in range(3)}
print(result)
A{0: {0: 0, 1: 0}, 1: {0: 0, 1: 1}, 2: {0: 0, 1: 2}}
B{0: {0: 0, 1: 1}, 1: {0: 0, 1: 1}, 2: {0: 0, 1: 1}}
C{0: {0: 0, 1: 0}, 1: {0: 1, 1: 1}, 2: {0: 2, 1: 2}}
DSyntaxError
Attempts:
2 left
๐Ÿ’ก Hint
Look carefully at the inner dictionary comprehension and how multiplication works.
โ“ Predict Output
advanced
2:00remaining
Result of dictionary comprehension with string keys
What will this code output?
Python
keys = ['a', 'b', 'c']
result = {k: ord(k) for k in keys}
print(result)
ATypeError
B{'a': 97, 'b': 98, 'c': 99}
C{'a': 'a', 'b': 'b', 'c': 'c'}
D{'a': 1, 'b': 2, 'c': 3}
Attempts:
2 left
๐Ÿ’ก Hint
The ord() function returns the Unicode code point of a character.
๐Ÿง  Conceptual
expert
2:00remaining
Number of items in dictionary comprehension result
How many items are in the dictionary created by this comprehension? {n: n//2 for n in range(10) if n % 3 != 0}
A3
B7
C10
D6
Attempts:
2 left
๐Ÿ’ก Hint
Count numbers from 0 to 9 excluding multiples of 3.