How to Remove a Key from a Dictionary in Python
To remove a key from a dictionary in Python, use
pop(key) to remove and return the value, or del dict[key] to delete the key without returning. Both methods remove the key and its value from the dictionary.Syntax
There are two common ways to remove a key from a dictionary:
dict.pop(key, default): Removes the key and returns its value. If the key is not found, returnsdefaultif provided, otherwise raisesKeyError.del dict[key]: Deletes the key and its value. RaisesKeyErrorif the key does not exist.
python
value = dict.pop(key, default) del dict[key]
Example
This example shows how to remove a key using pop() and del. It also shows what happens if the key is missing.
python
my_dict = {'apple': 5, 'banana': 3, 'cherry': 7}
# Remove 'banana' using pop and get its value
banana_count = my_dict.pop('banana')
print('Removed banana count:', banana_count)
print('Dictionary after pop:', my_dict)
# Remove 'apple' using del
del my_dict['apple']
print('Dictionary after del:', my_dict)
# Using pop with default to avoid error
orange_count = my_dict.pop('orange', 0)
print('Removed orange count (default):', orange_count)
# Using del on missing key raises error
try:
del my_dict['orange']
except KeyError:
print('KeyError: orange not found')Output
Removed banana count: 3
Dictionary after pop: {'apple': 5, 'cherry': 7}
Dictionary after del: {'cherry': 7}
Removed orange count (default): 0
KeyError: orange not found
Common Pitfalls
Trying to remove a key that does not exist without handling errors causes a KeyError. Using pop() without a default value or del on a missing key will raise this error.
Always provide a default value to pop() or use in to check if the key exists before deleting.
python
my_dict = {'a': 1, 'b': 2}
# Wrong: raises KeyError if key missing
# my_dict.pop('c')
# Right: provide default to avoid error
value = my_dict.pop('c', None)
print('Value:', value) # prints None
# Wrong: raises KeyError if key missing
# del my_dict['c']
# Right: check before deleting
if 'c' in my_dict:
del my_dict['c']
else:
print('Key c not found, cannot delete')Output
Value: None
Key c not found, cannot delete
Quick Reference
Summary of methods to remove keys from a dictionary:
| Method | Description | Error if Key Missing? |
|---|---|---|
pop(key) | Removes key and returns value | Yes, unless default provided |
pop(key, default) | Removes key and returns value or default | No |
del dict[key] | Deletes key and value | Yes |
popitem() | Removes and returns last inserted key-value pair | Yes if dict empty |
Key Takeaways
Use
pop(key) to remove a key and get its value safely with a default.Use
del dict[key] to delete a key but check if it exists to avoid errors.Providing a default to
pop() prevents KeyError when key is missing.Always handle missing keys to avoid runtime errors when removing keys.
Use
popitem() to remove the last inserted key-value pair if needed.