Remove Key from a Dictionary in Python
In Python, you can remove a key from a dictionary using the following methods:
(1) Using pop() method
The pop()
method removes the key and returns its value.
For example:
person = {"name": "James", "age": 35, "city": "New York"}
removed_item = person.pop("city")
print(removed_item) # Output: New York
print(person) # Output: {'name': 'James', 'age': 35}
You can also provide a default value to return if the key doesn’t exist in the dictionary.
person = {"name": "James", "age": 35}
removed_item = person.pop("city", "Not found")
print(removed_item) # Output: Not found
print(person) # Output: {'name': 'James', 'age': 35}
If no default value is provided and the key is missing, the pop()
method raises KeyError
.
(2) Using del statement
The del
statement removes the key-value pair from a dictionary.
For example:
person = {"name": "James", "age": 35, "city": "New York"}
del person["city"]
print(person) # Output: {'name': 'James', 'age': 35}
If the key doesn’t exist, it will raise KeyError
. You can handle this with a try-except
block.
person = {"name": "James", "age": 35}
try:
del person["city"]
except KeyError:
print("Key not found")
print(person)
Output:
Key not found
{'name': 'James', 'age': 35}
(3) Using popitem() method
The popitem()
method removes and returns the last inserted key-value pair from a dictionary as a tuple.
Before Python version 3.7, it removes and returns the random key-value pair as a tuple.
For example:
person = {"name": "James", "age": 35, "city": "New York"}
popped_item = person.popitem()
print(popped_item)
print(person)
Output:
('city', 'New York')
{'name': 'James', 'age': 35}
Which methods to use
Use del
statement to remove a key when you don’t need its value. This is the most efficient method to delete a key from a dictionary.
Use pop()
method to remove a key and retrieve its value.
Use popitem()
to remove and return the last inserted key-value pair.