Editor

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

remove_key_from_dictionary.py
student = {"name": "Riya", "age": 16, "city": "Pune", "grade": "A"}
print("Before:", student)
del student["city"] # remove a key you know is there
grade = student.pop("grade") # remove a key and get its value back
print("Removed grade:", grade)
email = student.pop("email", None) # a missing key with a default: no error
print("Removed email:", email)
print("After:", student)
Output
Before: {'name': 'Riya', 'age': 16, 'city': 'Pune', 'grade': 'A'}
Removed grade: A
Removed email: None
After: {'name': 'Riya', 'age': 16}

How it works

  1. del student["city"] deletes the key and its value, and raises a KeyError if the key is not there.
  2. student.pop("grade") deletes the key and returns its value, which is handy when you still need it.
  3. pop("email", None) returns the default None when the key is missing, instead of raising an error.
  4. The dictionary is changed in place, so student itself loses the removed entries.

Other ways to write it

Checking first, or catching the error

Checking first, or catching the error
student = {"name": "Riya", "age": 16}
key = "city" # or: key = input("Key to remove: ")
if key in student:
del student[key]
print("Removed", key)
else:
print(key, "is not a key, so nothing was removed")
try:
del student["city"]
except KeyError:
print("del raised a KeyError for the missing key city")
Output
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

Building a new dictionary without some keys
student = {"name": "Riya", "age": 16, "city": "Pune", "grade": "A"}
unwanted = ["age", "city"]
public = {key: value for key, value in student.items() if key not in unwanted}
print("Original:", student)
print("Without age and city:", public)
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises