Which method removes a specific key from a dictionary and returns its value?
A
remove() B
discard() C
pop() D
delete()
Analysis & Theory
`pop()` removes the specified key and returns the value. If the key is missing, it raises a KeyError.
What does the `popitem()` method do?
A
Removes a specific key-value pair B
Removes the last inserted key-value pair C
Removes all items D
Removes the first key-value pair
Analysis & Theory
`popitem()` removes the last inserted key-value pair in Python 3.7+.
Which method removes all items from a dictionary?
A
remove() B
clear() C
popitem() D
discard()
Analysis & Theory
`clear()` removes all items, resulting in an empty dictionary.
What happens if you try to `pop()` a key that does not exist?
A
Returns None B
Adds the key with default value C
Raises a KeyError D
Returns an empty dictionary
Analysis & Theory
`pop()` raises a KeyError if the key does not exist and no default is provided.
What will this output?
d = {'a': 1, 'b': 2}
d.pop('a')
print(d)
A
{'a': 1, 'b': 2} B
{'b': 2} C
{} D
Error
Analysis & Theory
`pop('a')` removes the key `'a'` and its value.
What does this return?
d = {'x': 5, 'y': 10}
print(d.pop('z', 0))
A
KeyError B
None C
0 D
z
Analysis & Theory
If the key does not exist, the second argument to `pop()` is returned as default.
Which of the following is NOT a valid way to remove items from a dictionary?
A
del dict['key'] B
dict.pop('key') C
dict.remove('key') D
dict.clear()
Analysis & Theory
Dictionaries do not have a `remove()` method.
What happens if you use `popitem()` on an empty dictionary?
A
Returns None B
Raises a KeyError C
Returns an empty tuple D
Deletes the dictionary
Analysis & Theory
`popitem()` raises a `KeyError` if the dictionary is empty.
What does the `del` keyword do when used with a dictionary key?
A
Deletes the dictionary B
Clears all values C
Removes the specified key and value D
Raises an error
Analysis & Theory
`del dict['key']` deletes the key-value pair from the dictionary.
How can you safely delete a key that may or may not exist?
A
Use del without checking B
Use dict.remove() C
Use dict.pop(key, default) D
Use dict.append(None)
Analysis & Theory
`pop(key, default)` prevents an error by returning the default value if the key is missing.