Removing a key from a Python Dictionary
In this tutorial, we are gonna learn about removing a key from a Python Dictionary.
I’m creating a dictionary in Python:
my_dict = { "Hello": 10, "Bye" : 20, "Yes": 40, "No" : 30 }
Now, the above dictionary has KEYS – ‘Hello’, ‘Bye’, ‘Yes’, and ‘No’, and they all have values of 10,20,40,30 respectively.
So our task here is to remove a key from the dictionary in Python. It is a pretty simple task and we are gonna do this by many methods. Hence, let’s begin.
Remove key from a dictionary using pop method
Here we are going to use the pop method which is the easiest way to remove a key from the dictionary in Python.
#removing key using pop #removes No result = my_dict.pop("No",None) print("Updated Dictionary :" , my_dict)
OUTPUT:
Updated Dictionary : {'Hello': 10, 'Bye': 20, 'Yes': 40}
Using del keyword to remove a key from a Python dictionary
Here we are going to use del keyword to remove a key from the dictionary in Python which is very easy to do.
#removing key using del #removes Bye if "Bye" in my_dict: del my_dict["Bye"] print("Updated Dictionary :" , my_dict)
OUTPUT:
Updated Dictionary : {'Hello': 10, 'Yes': 40, 'No': 30}
Deleting a key from a dict using items() +dict comprehension
In this method we will use items() + dict comprehension to remove a key from the dictionary in Python.
# Using items() + dict comprehension to remove a key # removes Yes new_dict = {key:val for key, val in my_dict.items() if key != 'Yes'} # Printing dictionary after removal print ("Updated Dictionary : " + str(new_dict))
OUTPUT:
Updated Dictionary : {'Hello': 10, 'Bye': 20, 'No': 30}
Hence this is it, I hope this helps you.
Leave a Reply