remove key from dictionary python

Previous
Next

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.

countryDict={"India":"Delhi","China":"Beijing","Australia":"Canberra","UK":"London"} print("countryDict before pop:",countryDict) removedCapital=countryDict.pop("China") print("countryDict after pop:",countryDict) print("Removed capital:",removedCapital) #If you try to remove key which is not present in the key, then it will raise KeyError removedCountry=countryDict.pop("USA")

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.

countryDict={"India":"Delhi","China":"Beijing","Australia":"Canberra","UK":"London"} print("countryDict before pop:",countryDict) removedCapital=countryDict.pop("USA","Dummy") print("countryDict after pop:",countryDict)

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.

countryDict={"India":"Delhi","China":"Beijing","Australia":"Canberra","UK":"London"} print("countryDict before removing key china:",countryDict) if 'China' in countryDict: del countryDict['China'] print("countryDict after removing key china:",countryDict)

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.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog