Challenge - 5 Problems
Dictionary Iteration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of iterating dictionary keys
What is the output of this code?
my_dict = {'a': 1, 'b': 2, 'c': 3}
result = []
for key in my_dict:
result.append(key)
print(result)Python
my_dict = {'a': 1, 'b': 2, 'c': 3}
result = []
for key in my_dict:
result.append(key)
print(result)Attempts:
2 left
๐ก Hint
Iterating a dictionary by default goes over its keys.
โ Incorrect
When you loop over a dictionary, you get its keys one by one. So appending keys to a list results in ['a', 'b', 'c'].
โ Predict Output
intermediate2:00remaining
Output of iterating dictionary items
What is the output of this code?
my_dict = {'x': 10, 'y': 20}
result = []
for k, v in my_dict.items():
result.append((k, v))
print(result)Python
my_dict = {'x': 10, 'y': 20}
result = []
for k, v in my_dict.items():
result.append((k, v))
print(result)Attempts:
2 left
๐ก Hint
items() returns key-value pairs as tuples.
โ Incorrect
The items() method returns pairs of (key, value). Appending these pairs creates a list of tuples.
โ Predict Output
advanced2:00remaining
Output of modifying dictionary during iteration
What happens when you run this code?
my_dict = {'a': 1, 'b': 2}
for key in my_dict:
my_dict['c'] = 3
print(my_dict)Python
my_dict = {'a': 1, 'b': 2}
for key in my_dict:
my_dict['c'] = 3
print(my_dict)Attempts:
2 left
๐ก Hint
Changing a dictionary while looping over it causes an error.
โ Incorrect
Python does not allow changing the size of a dictionary during iteration. Adding a new key causes a RuntimeError.
๐ง Conceptual
advanced2:00remaining
Number of items after filtering dictionary keys
Given this code, how many items will the resulting dictionary have?
original = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
filtered = {k: v for k, v in original.items() if v % 2 == 0}
print(len(filtered))Python
original = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
filtered = {k: v for k, v in original.items() if v % 2 == 0}
print(len(filtered))Attempts:
2 left
๐ก Hint
Count how many values are even numbers.
โ Incorrect
Only values 2 and 4 are even, so filtered dictionary has 2 items.
๐ง Debug
expert2:00remaining
Identify the error in dictionary iteration code
What error does this code raise?
data = {'x': 5, 'y': 10}
for key, value in data:
print(key, value)Python
data = {'x': 5, 'y': 10}
for key, value in data:
print(key, value)Attempts:
2 left
๐ก Hint
Iterating a dictionary yields keys, which are strings here.
โ Incorrect
Loop tries to unpack each key (a string) into two variables, causing ValueError: not enough values to unpack (expected 2, got 1).