Challenge - 5 Problems
Dictionary Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of dictionary keys() method
What is the output of this code snippet?
Python
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(list(my_dict.keys()))Attempts:
2 left
๐ก Hint
The keys() method returns a view of the dictionary's keys. Converting it to a list shows the keys as a list.
โ Incorrect
The keys() method returns a view object showing the keys. Converting it to a list gives ['a', 'b', 'c']. Option A shows the view object itself, not a list.
โ Predict Output
intermediate2:00remaining
Output of dictionary values() method
What will this code print?
Python
data = {'x': 10, 'y': 20}
vals = data.values()
print(sum(vals))Attempts:
2 left
๐ก Hint
The values() method returns a view of values which can be summed directly.
โ Incorrect
The values() method returns a view of the dictionary's values. sum() can add these numbers directly, resulting in 30.
โ Predict Output
advanced2:00remaining
Output of iterating dictionary items
What is the output of this code?
Python
d = {'one': 1, 'two': 2}
for k, v in d.items():
print(f"{k}:{v}")Attempts:
2 left
๐ก Hint
items() returns key-value pairs which are unpacked in the loop.
โ Incorrect
The loop unpacks each key-value pair and prints them in the format key:value on separate lines.
โ Predict Output
advanced2:00remaining
Length of dictionary keys view
What does this code print?
Python
my_dict = {1: 'a', 2: 'b', 3: 'c'}
keys_view = my_dict.keys()
print(len(keys_view))Attempts:
2 left
๐ก Hint
The keys view supports len() to get the number of keys.
โ Incorrect
The keys() method returns a view of keys which supports len(), returning the number of keys in the dictionary.
โ Predict Output
expert2:00remaining
Output of modifying dictionary during iteration
What happens when this code runs?
Python
d = {'a': 1, 'b': 2, 'c': 3}
for k in d.keys():
if k == 'b':
d.pop(k)
print(d)Attempts:
2 left
๐ก Hint
Modifying a dictionary while iterating over its keys causes an error.
โ Incorrect
Python raises a RuntimeError if the dictionary size changes during iteration over keys or items.