Remove Key from Dictionary Python

In this tutorial, we will see how to remove key from the dictionary in Python.
There are multiple ways to do it.Let’s explore a different way of deleting a key from the dictionary.

Using pop method

You can use pop method to remove key from dictionary.This is cleanest way to delete key from dictionary.

Output:

countryDict before pop: {‘India’: ‘Delhi’, ‘China’: ‘Beijing’, ‘Australia’: ‘Canberra’, ‘UK’: ‘London’}
countryDict after pop: {‘India’: ‘Delhi’, ‘Australia’: ‘Canberra’, ‘UK’: ‘London’}
Removed capital: Beijing
—————————————————————————
KeyError Traceback (most recent call last)
in ()
6
7 #If you try to remove key which is not present in the key, then it will raise KeyError
—-> 8 removedCountry=countryDict.pop(“USA”)
9

KeyError: ‘USA’

As you can see, when we are successfully able to delete key "china" from dictionary but when we try to remove key which is not present in the dictionary then we are getting KeyError.
If you pass default value to pop method then you won’t get KeyError.

Output:

countryDict before pop: {‘India’: ‘Delhi’, ‘China’: ‘Beijing’, ‘Australia’: ‘Canberra’, ‘UK’: ‘London’}
countryDict after pop: {‘India’: ‘Delhi’, ‘China’: ‘Beijing’, ‘Australia’: ‘Canberra’, ‘UK’: ‘London’}

As you can see, when we provided default value with pop method, we did not get keyError and dict did not change.

Using del operator

You can also use del operator to delete key from dictionary.
Let’s understand with the help of example.

Output:

countryDict before removing key china: {‘India’: ‘Delhi’, ‘China’: ‘Beijing’, ‘Australia’: ‘Canberra’, ‘UK’: ‘London’}
countryDict adter removing key china: {‘India’: ‘Delhi’, ‘Australia’: ‘Canberra’, ‘UK’: ‘London’}

That’s all about removing key from dictionary in python.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *