In Python, we can remove a key from a dictionary using the following approaches.
del
keywordThe del
keyword is used to remove a key present in the dictionary. If the key is not present in the dictionary, it raises a KeyError
exception.
Let's see an example of this keyword in the code snippet below.
# create a dictionarydata = {'name': 'Shubham','designation': 'Software Engineer','age': 22}# print dataprint("Before deleting")print(data)# remove key 'age'del data['age']# print dataprint("After deleting")print(data)
data
.data
to the console.age
from the dictionary using the del
keyword.data
to the console.pop()
methodThe pop()
method is also used to remove a key present in the dictionary. If the key is not present in the dictionary, it raises an KeyError
exception.
The advantage of using this method over the del
keyword is that we can provide a desired value when trying to remove a key that is not present in the dictionary. Moreover, this method returns the value of the key that is removed.
Let's see an example of this method in the code snippet below.
# create a dictionarydata = {'name': 'Shubham','designation': 'Software Engineer','age': 22}# print dataprint("Before deleting")print(data)# remove key 'age'data.pop('age', 'Not found')# print dataprint("After deleting")print(data)
data
.data
to the console.age
from the dictionary using the pop()
method.data
to the console.