Recall & Review
beginner
How do you remove a key-value pair from a dictionary using the
del statement?Use
del dict[key] to remove the entry with the specified key from the dictionary.Click to reveal answer
beginner
What does the
pop() method do in a dictionary?The
pop(key) method removes the key-value pair with the given key and returns its value. If the key is not found, it raises a KeyError unless a default value is provided.Click to reveal answer
intermediate
How can you safely remove a key from a dictionary without causing an error if the key does not exist?
Use
pop(key, default_value) where default_value is returned if the key is missing, preventing an error.Click to reveal answer
intermediate
What is the difference between
popitem() and pop() in dictionaries?popitem() removes and returns the last inserted key-value pair as a tuple, while pop(key) removes the pair with the specified key.Click to reveal answer
advanced
Can you remove multiple entries from a dictionary at once? If yes, how?
Yes, by using a loop to remove keys one by one or by creating a new dictionary excluding unwanted keys.
Click to reveal answer
Which statement removes the key 'age' from the dictionary
person?✗ Incorrect
The
del statement with the key removes that entry from the dictionary.What does
person.pop('name') return?✗ Incorrect
pop(key) returns the value for the key and removes the key-value pair.How can you avoid an error when removing a key that might not exist?
✗ Incorrect
Providing a default value to
pop() prevents errors if the key is missing.What does
popitem() do?✗ Incorrect
popitem() removes and returns the last inserted pair as a tuple.Which method is NOT used to remove entries from a dictionary?
✗ Incorrect
remove() is not a dictionary method; it is used with lists.Explain three ways to remove entries from a Python dictionary and when to use each.
Think about whether you want the removed value or just to delete.
You got /3 concepts.
How can you safely remove a key from a dictionary without causing an error if the key does not exist?
Consider methods that provide a fallback value.
You got /3 concepts.