![]() |
VOOZH | about |
Sometimes, we may need to remove a specific item from a dictionary to update its structure. For example, consider the dictionary d = {'x': 100, 'y': 200, 'z': 300}. If we want to remove the item associated with the key 'y', several methods can help achieve this. Let’s explore these methods.
pop() method is a straightforward way to remove a dictionary item by specifying its key. If the key exists, it removes the item and returns its value.
{'x': 100, 'z': 300}
200
Explanation:
Let's explore some more ways and see how we can remove dictionary item.
del() statement allows us to remove a dictionary item by its key. Unlike pop(), it does not return the removed value.
{'x': 100, 'z': 300}
Explanation:
If we need to remove an item based on its key, we can create a new dictionary that excludes the specified key.
{'x': 100, 'z': 300}
Explanation:
If the item to be removed is the last one added, popitem() method can be used. It removes and returns the last key-value pair in the dictionary.
{'x': 100, 'y': 200}
('z', 300)
Explanation: