Sometimes you want to delete items from a dictionary when they are no longer needed or to clean up data.
0
0
Removing dictionary entries in Python
Introduction
You want to remove a user's data after they log out.
You need to delete expired items from a cache.
You want to update a dictionary by removing incorrect or outdated entries.
You want to filter out certain keys from a dictionary before processing.
Syntax
Python
my_dict = {'key1': 'value1', 'key2': 'value2'}
# Remove an entry by key
removed_value = my_dict.pop('key1')
# Remove an entry by key with default if key not found
removed_value = my_dict.pop('key3', None)
# Remove and return an arbitrary item
key, value = my_dict.popitem()
# Delete an entry by key without return
del my_dict['key2']pop(key) removes the key and returns its value. It raises an error if the key is missing.
pop(key, default) returns default if key is missing instead of error.
Examples
Removes key 'b' and returns its value 2.
Python
my_dict = {'a': 1, 'b': 2, 'c': 3}
removed_value = my_dict.pop('b')
print(my_dict)
print(removed_value)Key 'z' does not exist, so it returns 'Not found' and dictionary stays the same.
Python
my_dict = {'a': 1}
removed_value = my_dict.pop('z', 'Not found')
print(removed_value)
print(my_dict)popitem() on empty dictionary raises KeyError.
Python
my_dict = {}
# Using popitem on empty dict raises error
try:
my_dict.popitem()
except KeyError as error:
print('Error:', error)Deletes key 'x' without returning value. Dictionary becomes empty.
Python
my_dict = {'x': 10}
del my_dict['x']
print(my_dict)Sample Program
This program shows how to remove entries from a dictionary using pop and del. It also shows how to safely try to remove a key that might not exist.
Python
def print_dictionary_state(stage, dictionary): print(f"{stage}: {dictionary}") user_data = {'name': 'Alice', 'age': 30, 'city': 'Wonderland'} print_dictionary_state('Original dictionary', user_data) # Remove 'age' using pop removed_age = user_data.pop('age') print(f"Removed 'age' with value: {removed_age}") print_dictionary_state('After removing age', user_data) # Remove 'city' using del del user_data['city'] print_dictionary_state('After deleting city', user_data) # Try to remove 'country' with pop and default removed_country = user_data.pop('country', 'Not found') print(f"Attempted to remove 'country', got: {removed_country}") print_dictionary_state('Final dictionary', user_data)
OutputSuccess
Important Notes
Time complexity: Removing an entry by key is usually O(1).
Space complexity: No extra space is needed; the dictionary is modified in place.
Using pop with a default value helps avoid errors if the key is missing.
Using del on a missing key causes a KeyError, so be careful.
Summary
Use pop(key) to remove and get the value of a key.
Use pop(key, default) to avoid errors if the key is missing.
Use del dict[key] to remove a key without returning its value.