Challenge - 5 Problems
Dictionary Removal Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
What is the output after removing a key?
Consider the dictionary
d = {'a': 1, 'b': 2, 'c': 3}. What is the output after running d.pop('b') and then printing d?Python
d = {'a': 1, 'b': 2, 'c': 3}
d.pop('b')
print(d)Attempts:
2 left
๐ก Hint
The pop method removes the key and returns its value.
โ Incorrect
The pop method removes the specified key from the dictionary and returns its value. After popping 'b', the dictionary no longer contains 'b'.
โ Predict Output
intermediate2:00remaining
What happens when deleting a non-existent key?
Given
d = {'x': 10, 'y': 20}, what happens when you run del d['z']?Python
d = {'x': 10, 'y': 20}
del d['z']Attempts:
2 left
๐ก Hint
Deleting a key that does not exist causes an error.
โ Incorrect
Using del on a key that is not in the dictionary raises a KeyError because the key cannot be found.
โ Predict Output
advanced2:00remaining
What is the output after filtering dictionary entries?
What is the output of this code?
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
d = {k: v for k, v in d.items() if v % 2 == 0}
print(d)Python
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
d = {k: v for k, v in d.items() if v % 2 == 0}
print(d)Attempts:
2 left
๐ก Hint
Only keep items where the value is even.
โ Incorrect
The dictionary comprehension keeps only items where the value is divisible by 2 (even numbers). So keys 'b' and 'd' remain.
โ Predict Output
advanced2:00remaining
What is the output after using popitem()?
Given
d = {'x': 1, 'y': 2, 'z': 3}, what does d.popitem() return and what is the dictionary afterwards?Python
d = {'x': 1, 'y': 2, 'z': 3}
popped = d.popitem()
print(popped)
print(d)Attempts:
2 left
๐ก Hint
popitem removes and returns the last inserted item in Python 3.7+.
โ Incorrect
In Python 3.7 and later, dictionaries keep insertion order. popitem removes the last inserted key-value pair, which is ('z', 3).
๐ง Conceptual
expert2:00remaining
Which option causes a runtime error when removing dictionary entries?
Which of the following code snippets will cause a runtime error when trying to remove entries from a dictionary?
Attempts:
2 left
๐ก Hint
Modifying a dictionary while iterating over it can cause errors.
โ Incorrect
Deleting keys from a dictionary while iterating over it directly causes a RuntimeError due to dictionary size change during iteration.