![]() |
VOOZH | about |
Dictionaries in Python store data as key-value pairs. Often, we need to remove a specific key-value pair to modify or clean the dictionary. For instance, consider the dictionary d = {'a': 1, 'b': 2, 'c': 3}; we might want to remove the key 'b'. Let's explore different methods to achieve this.
del() statement is the most efficient way to remove an item by its key. It directly deletes the specified key-value pair from the dictionary.
{'a': 1, 'c': 3}
Explanation:
Let's explore some more ways and see how we can remove item from dictionary by key.
pop() method removes the key-value pair associated with a specific key and returns its value.
{'a': 1, 'c': 3}
2
Explanation:
This method creates a new dictionary by filtering out the key to be removed using dictionary comprehension.
{'a': 1, 'c': 3}
Explanation:
popitem() method removes the last inserted key-value pair from the dictionary. We can use this with manual checks to find and remove a specific key, although it is not recommended for targeted key removal.
{'a': 1, 'c': 3}
Explanation: