0
0
Pythonprogramming~20 mins

Removing dictionary entries in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Dictionary Removal Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2: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)
A{'a': 1, 'c': 3}
B{'b': 2, 'c': 3}
CKeyError
D{'a': 1, 'b': 2, 'c': 3}
Attempts:
2 left
๐Ÿ’ก Hint
The pop method removes the key and returns its value.
โ“ Predict Output
intermediate
2: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']
ANone
B{'x': 10, 'y': 20}
CKeyError
DSyntaxError
Attempts:
2 left
๐Ÿ’ก Hint
Deleting a key that does not exist causes an error.
โ“ Predict Output
advanced
2: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)
A{'b': 2, 'd': 4}
B{'a': 1, 'c': 3}
C{'a': 1, 'b': 2, 'c': 3, 'd': 4}
DTypeError
Attempts:
2 left
๐Ÿ’ก Hint
Only keep items where the value is even.
โ“ Predict Output
advanced
2: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)
A
('y', 2)
{'x': 1, 'z': 3}
B
('x', 1)
{'y': 2, 'z': 3}
C
KeyError
{'x': 1, 'y': 2, 'z': 3}
D
('z', 3)
{'x': 1, 'y': 2}
Attempts:
2 left
๐Ÿ’ก Hint
popitem removes and returns the last inserted item in Python 3.7+.
๐Ÿง  Conceptual
expert
2: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?
A
d = {'a': 1, 'b': 2}
keys = list(d.keys())
for key in keys:
    del d[key]
B
d = {'a': 1, 'b': 2}
for key in d:
    del d[key]
C
d = {'a': 1, 'b': 2}
d.pop('a')
D
d = {'a': 1, 'b': 2}
d.pop('c', None)
Attempts:
2 left
๐Ÿ’ก Hint
Modifying a dictionary while iterating over it can cause errors.