Python | Ways to remove a key from dictionary
Dictionary is used in manifold practical applications such as day-day programming, web development and AI/ML programming as well, making it a useful container overall. Hence, knowing shorthands for achieving different tasks related to dictionary usage always is a plus. This article deals with one such task of deleting a dictionary key-value pair from a dictionary.
Method 1 : Using del
del
keyword can be used to inplace delete the key that is present in the dictionary. One drawback that can be thought of using this is that is raises an exception if the key is not found and hence non-existence of key has to be handled.
Code #1 : Demonstrating key-value pair deletion using del
Output :
The dictionary before performing remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21} The dictionary after remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22}
Exception :
Traceback (most recent call last): File "/home/44db951e7011423359af4861d475458a.py", line 20, in del test_dict['Manjeet'] KeyError: 'Manjeet'
Method 2 : Using pop()
pop() can be used to delete a key and its value inplace. Advantage over using del
is that it provides the mechanism to print desired value if tried to remove a non-existing dict. pair. Second, it also returns the value of key that is being removed in addition to performing a simple delete operation.
Code #2 : Demonstrating key-value pair deletion using pop()
Output :
The dictionary before performing remove is : {'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21} The dictionary after remove is : {'Arushi': 22, 'Anuradha': 21, 'Haritha': 21} The removed key's value is : 21 The dictionary after remove is : {'Arushi': 22, 'Anuradha': 21, 'Haritha': 21} The removed key's value is : No Key found
Method 3 : Using items()
+ dict comprehension
items()
coupled with dict comprehension can also help us achieve task of key-value pair deletion but, it has drawback of not being an inplace dict. technique. Actually a new dict if created except for the key we don’t wish to include.
Code #3 : Demonstrating key-value pair deletion using items()
+ dict. comprehension
Output :
The dictionary before performing remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21} The dictionary after remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22}
No comments:
Post a Comment
Your feedback is highly appreciated and will help us to improve our content.