Python Remove Dictionary Items
Ways to Remove Items from a Dictionary
Python provides several methods to remove one or more items from a dictionary:
pop()
popitem()
del
clear()
Example 1: pop()
Method – Remove Specific Item
car = { "brand": "Ford", "model": "Mustang", "year": 1964 } car.pop("model") print(car)
Output:
{'brand': 'Ford', 'year': 1964}
Explanation: pop("model")
removes the item with key "model"
and returns its value.
Example 2: popitem()
Method – Remove Last Inserted Item
car = { "brand": "Ford", "model": "Mustang", "year": 1964 } car.popitem() print(car)
Output:
{'brand': 'Ford', 'model': 'Mustang'}
Explanation: popitem()
removes the last inserted key-value pair (in this case, "year": 1964
).
Example 3: del
Keyword – Remove Specific Item
car = { "brand": "Ford", "model": "Mustang", "year": 1964 } del car["year"] print(car)
Output:
{'brand': 'Ford', 'model': 'Mustang'}
Explanation: del
deletes the key "year"
and its value from the dictionary.
Example 4: del
Keyword – Delete Entire Dictionary
car = { "brand": "Ford", "model": "Mustang" } del car # print(car) # This would raise an error: NameError
Explanation: del car
completely deletes the dictionary from memory.
Example 5: clear()
Method – Remove All Items
car = { "brand": "Ford", "model": "Mustang" } car.clear() print(car)
Output:
{}
Explanation: clear()
removes all items but keeps the dictionary object itself.
Summary of Removal Methods
Method | What it does | Raises error if key not found? |
---|---|---|
pop(key) | Removes key-value by key | ✅ Yes |
popitem() | Removes last inserted key-value pair | ❌ No |
del | Removes item or entire dictionary | ✅ Yes |
clear() | Empties the dictionary | ❌ No |
Conclusion
Python makes it easy to remove items from dictionaries. Choose the method based on what you want to delete: a specific item, the last one, or all items.