How to remove a key from a Python dictionary

In Python, we can remove a key from a dictionary using the following approaches.

Approach 1: Using the del keyword

The 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 dictionary
data = {
'name': 'Shubham',
'designation': 'Software Engineer',
'age': 22
}
# print data
print("Before deleting")
print(data)
# remove key 'age'
del data['age']
# print data
print("After deleting")
print(data)

Explanation

  • Lines 2–6: We create a dictionary named data.
  • Lines 9–10: We print the dictionary data to the console.
  • Line 13: We remove the key age from the dictionary using the del keyword.
  • Line 15: We print the dictionary data to the console.

Approach 2: Using the pop() method

The 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 dictionary
data = {
'name': 'Shubham',
'designation': 'Software Engineer',
'age': 22
}
# print data
print("Before deleting")
print(data)
# remove key 'age'
data.pop('age', 'Not found')
# print data
print("After deleting")
print(data)

Explanation

  • Lines 2–6: We create a dictionary named data.
  • Lines 9–10: We print the dictionary data to the console.
  • Line 13: We remove the key age from the dictionary using the pop() method.
  • Line 15: We print the dictionary data to the console.

Free Resources