In Python, dictionaries are mutable collections of key–value pairs. Sometimes you need to remove data: a single key, the last inserted item, or even clear everything. Python provides multiple ways to do this: pop(), popitem(), the del statement, and clear().
pop(key) removes a specific key and returns its value.popitem() removes and returns the last inserted key–value pair.del can delete a specific key or the entire dictionary object.clear() removes all items but keeps the dictionary itself.pop() or del can raise KeyError.dict.pop(key[, default]) → removes key and returns its value; returns default if provided and key is missing.dict.popitem() → removes and returns the last inserted (key, value) pair.del dict[key] → deletes the entry with the given key.del dict_name → deletes the entire dictionary object.dict.clear() → empties the dictionary, resulting in {}.The pop() method removes a specific key from the dictionary and returns its corresponding value.
person = {"name": "Alice", "age": 25, "city": "New York"}
removed_value = person.pop("age")
print(removed_value) # 25
print(person) # {'name': 'Alice', 'city': 'New York'}
The popitem() method removes and returns the last inserted key–value pair from the dictionary.
person = {"name": "Alice", "city": "New York"}
last_item = person.popitem()
print(last_item) # ('city', 'New York')
print(person) # {'name': 'Alice'}
The del statement can remove a specific key or delete the entire dictionary from memory.
person = {"name": "Alice", "city": "New York"}
del person["city"]
print(person) # {'name': 'Alice'}
# del person # Deletes the entire dictionary
The clear() method removes all key–value pairs but keeps the dictionary object itself.
person = {"name": "Alice", "age": 25}
person.clear()
print(person) # {}
pop() example, "age" is removed and its value 25 is printed. The remaining dictionary is {'name': 'Alice', 'city': 'New York'}.popitem() example, the last inserted pair ('city', 'New York') is removed, leaving {'name': 'Alice'}.del example, person["city"] is deleted, so the dictionary becomes {'name': 'Alice'}.clear() example, all items are removed and the dictionary becomes an empty dictionary {}.pop() when you need the value of the key you are removing.popitem() is useful for LIFO-style removal in Python 3.7+ where dicts preserve insertion order.del is more general and can delete specific keys or entire dictionary objects.clear() keeps the dictionary object but empties its contents.KeyError with pop(), provide a default: dict.pop("key", None).pop(); print the removed value and the updated dictionary.popitem() on a multi-item dictionary and observe which item is removed.del and then try deleting the same key again to see what error you get.clear() on a dictionary and print it to confirm that it is now empty.