Use the del statement (del d[key]) when you know the key exists, or the .pop(key, default) method when you want to remove the key and retrieve its value—or safely ignore missing keys without raising a KeyError.
Basic Example
# 1. Define a sample dictionary
product = {"id": 501, "name": "Laptop", "price": 1200, "discount": 10}
# 2. Delete a specific key using 'del' (raises KeyError if missing)
del product["discount"]
# 3. Delete and return a value using '.pop()' (safe with a default fallback)
removed_price = product.pop("price", None)
print(removed_price) # Output: 1200
print(product) # Output: {'id': 501, 'name': 'Laptop'}
Key Details & Alternative Methods
- Handling missing keys (
KeyError): Runningdel product["stock"]when"stock"is not in the dictionary raises aKeyError. To avoid errors, either pass a fallback default to.pop("stock", None)or check membership first (if "stock" in product: del product["stock"]). - Deleting the last inserted item (
.popitem()): Since Python 3.7+, dictionaries preserve insertion order. Callingproduct.popitem()removes and returns the most recently added(key, value)pair as a tuple. - Deleting without mutating the original (dictionary comprehension): If you need a new dictionary without one or more specific keys while keeping the original intact:
keys_to_exclude = {"price", "discount"} clean_product = {k: v for k, v in product.items() if k not in keys_to_exclude}
Comparison of Dictionary Deletion Methods
| Method | Target | Behavior if Key Missing | Returns Deleted Data? | Mutates Original? |
|---|---|---|---|---|
del d[key] |
Specific key | Raises KeyError |
No | Yes |
d.pop(key, default) |
Specific key | Returns default (or raises KeyError if omitted) |
Yes (the value) | Yes |
d.popitem() |
Last inserted item | Raises KeyError (if dict is empty) |
Yes ((key, value) tuple) |
Yes |
| Dict comprehension | One or multiple keys | Safely ignored | Returns new dict |
No |
You must log in or register to comment.
