![]() |
VOOZH | about |
Given a dictionary, the task is to remove a specific key from it. For example:
Input: {"a": 1, "b": 2, "c": 3}
Removing key "b"
Output: {'a': 1, 'c': 3}
Let's explore some methods to see how we can remove a key from dictionary.
pop() method removes a specific key from the dictionary and returns its corresponding value.
{'name': 'Nikki', 'city': 'New York'}
25
Explanation: Notice that after using the pop() method, key - "age" is completely removed from the dictionary.
del() statement deletes a key-value pair from the dictionary directly and does not return the value making it ideal when the value is not needed.
{'name': 'Nikki', 'age': 25}
We can also provide a default value to the pop() method, ensuring no error occurs if the key doesn’t exist.
{'name': 'Niiki', 'age': 25, 'city': 'New York'}
Key not found
Explanation: a.pop("country", "Key not found") removes "country" if it exists and returns "Key not found" if the key is missing, avoiding errors.
If we want to remove the last key-value pair in the dictionary, popitem() is a quick way to do it. Useful for LIFO operations.
{'name': 'Nikki', 'age': 25}
('city', 'New York')
Explanation: popitem() method removes the last inserted key-value pair from the dictionary.