Remove Dictionary Items
Removing Items
Python provides multiple ways to remove items from a dictionary:
- **pop(key)**: Removes the item with the specified key and returns its value
- **popitem()**: Removes and returns the last inserted key-value pair (in insertion order, Python 3.7+)
- **del**: Deletes the item with the specified key
- **clear()**: Removes all items from the dictionary
Example
# Removing items from a dictionary
person = {"name": "John", "age": 30, "city": "New York", "country": "USA"}
# Using pop()
age = person.pop("age")
print("Removed age:", age)
print(person)
# Using popitem()
last_item = person.popitem()
print("Removed last item:", last_item)
print(person)
# Using del
del person["city"]
print(person)
# Using clear()
person.clear()
print(person)
Output
Removed age: 30 {'name': 'John', 'city': 'New York', 'country': 'USA'} Removed last item: ('country', 'USA') {'name': 'John', 'city': 'New York'} {'name': 'John'} {}
Safely Removing Items
To avoid `KeyError` when removing items that may not exist, you can use safe methods or checks:
Example
# Safely removing items
person = {"name": "John", "age": 30}
# pop() with default value if key not found
country = person.pop("country", "Unknown")
print("Country:", country)
print(person)
# Check existence before deleting
if "city" in person:
del person["city"]
else:
print("City key does not exist")
Output
Country: Unknown {'name': 'John', 'age': 30} City key does not exist
Filtering Dictionaries
Instead of removing keys directly, you can create a new dictionary containing only the items you want using dictionary comprehensions.
Example
# Filtering a dictionary
person = {"name": "John", "age": 30, "city": "New York", "country": "USA"}
# Keep only certain keys
keys_to_keep = {"name", "age"}
filtered_person = {k: v for k, v in person.items() if k in keys_to_keep}
print("Filtered:", filtered_person)
# Remove certain keys by excluding them
keys_to_remove = {"city", "country"}
filtered_person2 = {k: v for k, v in person.items() if k not in keys_to_remove}
print("Filtered 2:", filtered_person2)
Output
Filtered: {'name': 'John', 'age': 30} Filtered 2: {'name': 'John', 'age': 30}