![]() |
VOOZH | about |
We are given a dictionary and our task is to delete a specific key-value pair only if the key exists. For example, if we have a dictionary 'd' with values {'x': 10, 'y': 20, 'z': 30} and we want to remove the key 'y', we should first check if 'y' exists before deleting it. After deletion, the updated dictionary will be {'x': 10, 'z': 30}. Let's explore different methods to achieve this in Python.
pop() method allows us to delete a key if it exists, while safely handling cases where the key might not be present.
{'x': 10, 'z': 30}
Explanation: pop() method removes the key 'y' from the dictionary if it exists and the second argument None, ensures no error is raised if the key is absent.
Let's explores some more methods and see how we can delete a python dictionary item if the key exists.
del() keyword can be combined with an in check to safely delete a key only if it exists.
{'x': 10, 'z': 30}
Explanation:
We can use a try-except block to handle the deletion and avoid errors if the key is not found.
{'x': 10, 'z': 30}
Explanation:
We can use the get() method to check for the key’s existence before using del().
{'x': 10, 'z': 30}
Explanation: