Python Program to Remove a Key from a Dictionary
Beginner · Dictionaries
This program removes entries from a dictionary in the three common ways: del, pop(), and pop() with a default, which does not fail when the key is missing. Removing a key also removes its value.
Program
Before: {'name': 'Riya', 'age': 16, 'city': 'Pune', 'grade': 'A'}
Removed grade: A
Removed email: None
After: {'name': 'Riya', 'age': 16}How it works
del student["city"]deletes the key and its value, and raises a KeyError if the key is not there.student.pop("grade")deletes the key and returns its value, which is handy when you still need it.pop("email", None)returns the defaultNonewhen the key is missing, instead of raising an error.- The dictionary is changed in place, so
studentitself loses the removed entries.
Other ways to write it
Checking first, or catching the error
city is not a key, so nothing was removed del raised a KeyError for the missing key city
Checking with in before del, or catching KeyError, are the two safe ways to delete a key that may not exist.
Building a new dictionary without some keys
Original: {'name': 'Riya', 'age': 16, 'city': 'Pune', 'grade': 'A'}
Without age and city: {'name': 'Riya', 'grade': 'A'}The dictionary comprehension copies only the entries you want to keep, so several keys go at once and the original stays unchanged.
Try it yourself
Use student.popitem() to remove the last entry added and print what it returns.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises