Open In App

Python - Ways to remove a key from dictionary

Last Updated : 29 Oct, 2025
Comments
Improve
Suggest changes
37 Likes
Like
Report

Given a dictionary, the task is to remove a specific key from it. For example:

Input: {"a": 1, "b": 2, "c": 3}
Removing key "b"
Output: {'a': 1, 'c': 3}

Let's explore some methods to see how we can remove a key from dictionary.

Using pop()

pop() method removes a specific key from the dictionary and returns its corresponding value.

Python
a = {"name": "Nikki", "age": 25, "city": "New York"}
rv = a.pop("age")
print(a)  
print(rv)  

Output
{'name': 'Nikki', 'city': 'New York'}
25

Explanation: Notice that after using the pop() method, key - "age" is completely removed from the dictionary.

Using del()

del() statement deletes a key-value pair from the dictionary directly and does not return the value making it ideal when the value is not needed.

Python
a = {"name": "Nikki", "age": 25, "city": "New York"}
del a["city"]
print(a)  

Output
{'name': 'Nikki', 'age': 25}

Using pop() with Default Value

We can also provide a default value to the pop() method, ensuring no error occurs if the key doesn’t exist.

Python
a = {"name": "Niiki", "age": 25, "city": "New York"}
rv = a.pop("country", "Key not found")
print(a)  
print(rv)  

Output
{'name': 'Niiki', 'age': 25, 'city': 'New York'}
Key not found

Explanation: a.pop("country", "Key not found") removes "country" if it exists and returns "Key not found" if the key is missing, avoiding errors.

Using popitem() for Last Key Removal

If we want to remove the last key-value pair in the dictionary, popitem() is a quick way to do it. Useful for LIFO operations.

Python
a = {"name": "Nikki", "age": 25, "city": "New York"}
c = a.popitem()
print(a)  
print(c)  

Output
{'name': 'Nikki', 'age': 25}
('city', 'New York')

Explanation: popitem() method removes the last inserted key-value pair from the dictionary.


Explore