0
0
Pythonprogramming~20 mins

Dictionary iteration in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Dictionary Iteration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2: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)
A['a', 1, 'b', 2, 'c', 3]
B[1, 2, 3]
C['a', 'b', 'c']
D[]
Attempts:
2 left
๐Ÿ’ก Hint
Iterating a dictionary by default goes over its keys.
โ“ Predict Output
intermediate
2: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)
A[('x', 10), ('y', 20)]
B['x', 'y']
C[10, 20]
D[('x', 'y'), (10, 20)]
Attempts:
2 left
๐Ÿ’ก Hint
items() returns key-value pairs as tuples.
โ“ Predict Output
advanced
2: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)
A{'a': 1, 'b': 2, 'c': 3}
BRuntimeError: dictionary changed size during iteration
C{'a': 1, 'b': 2}
DSyntaxError
Attempts:
2 left
๐Ÿ’ก Hint
Changing a dictionary while looping over it causes an error.
๐Ÿง  Conceptual
advanced
2: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))
A1
B3
C4
D2
Attempts:
2 left
๐Ÿ’ก Hint
Count how many values are even numbers.
๐Ÿ”ง Debug
expert
2: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)
AValueError: not enough values to unpack (expected 2, got 1)
BKeyError
CSyntaxError
DNo error, prints keys and values
Attempts:
2 left
๐Ÿ’ก Hint
Iterating a dictionary yields keys, which are strings here.