![]() |
VOOZH | about |
We are given a dictionary and a key and our task is to remove the key from the dictionary if it exists. For example, d = {"a": 10, "b": 20, "c": 30} and key to remove is "b" then output will be {"a": 10, "c": 30}.
pop() method allows us to remove a key from a dictionary while specifying a default value to handle cases where the key doesn’t exist.
{'a': 1, 'c': 3}
Explanation:
Let's explore some more ways and see how we can remove key from dictionary if it exists.
Table of Content
The del() keyword can be used to delete a key after confirming its presence with the in operator.
{'a': 1, 'c': 3}
Explanation:
We can use get() to check for a key before using del().
{'a': 1, 'c': 3}
Explanation:
While pop() can be used directly without a default value, it raises a KeyError if the key doesn’t exist and that is why we use try and except to manage that efficiently
{'a': 1, 'c': 3}
Explanation: