Delete a Key-Value Pair from a Python Dictionary
Learn how to remove dictionary items with del and pop(), handle missing keys, and verify changes in Python.
Dictionary Items Are Key-Value Pairs
A dictionary is a mutable Python mapping that associates unique keys with values. A key-value pair is one entry in the dictionary: the key identifies the entry, and the value is the data stored under that key.
person = {
'eye_color': 'brown',
'height': 175,
'weight': 70
}In this example, 'height' is a key and 175 is its value. Deleting a dictionary item removes both the selected key and its associated value.
Because dictionaries are mutable, they can be changed after creation. You can add, update, and remove key-value pairs without creating a new dictionary.
Delete an Item with del
Use the del statement to remove a dictionary item by its key:
del dictionary[key]The key inside the square brackets identifies which item to remove. The statement changes the original dictionary in place; it does not create a modified copy.
Worked Example
Suppose a dictionary stores descriptive attributes. To remove the height entry, use its key with del:
person = {
'eye_color': 'brown',
'height': 175,
'weight': 70
}
del person['height']
print(person)Output:
{'eye_color': 'brown', 'weight': 70}The 'height' key and the value 175 are gone. The other key-value pairs remain in the dictionary.
Inspect the Dictionary After Deletion
When learning or debugging, print the dictionary after the deletion statement:
settings = {'theme': 'dark', 'font_size': 14}
del settings['font_size']
print(settings)
# {'theme': 'dark'}Checking the resulting dictionary confirms that the intended item was removed.
Missing Keys and KeyError
If the requested key does not exist, del dictionary[key] raises a KeyError. A KeyError is an exception raised when code requests an absent dictionary key.
person = {'eye_color': 'brown'}
del person['height'] # KeyError: 'height'A key can be absent because it was never added, was already deleted, or was spelled or capitalized differently. Dictionary keys are case-sensitive, so 'Height' and 'height' are different keys.
Check for the Key Before Deleting
The in operator tests whether a key exists in a dictionary. Use it to guard the deletion:
person = {'eye_color': 'brown', 'height': 175}
if 'height' in person:
del person['height']
print('Height removed')
else:
print('Height was not present')
print(person)The condition is true only when 'height' is a key in person. The indentation makes the deletion run only when the key is present.
Use pop() When You Need the Removed Value
del removes an item but does not return its value. The dictionary method pop() removes an item and returns the value that was stored under its key.
person = {
'eye_color': 'brown',
'height': 175,
'weight': 70
}
removed_height = person.pop('height')
print(removed_height) # 175
print(person) # {'eye_color': 'brown', 'weight': 70}Assigning the result to removed_height lets the program use the removed value afterward.
Provide a Fallback with pop(key, default)
Use dict.pop(key, default) when the key may be absent and you want a fallback value instead of a KeyError:
person = {'eye_color': 'brown'}
removed_height = person.pop('height', None)
print(removed_height) # None
print(person) # {'eye_color': 'brown'}If 'height' exists, pop() removes it and returns its value. If it does not exist, pop() returns None in this example and leaves the dictionary unchanged.
Choose a default that clearly represents “not found” for your program:
removed_color = person.pop('eye_color', 'unknown')
print(removed_color) # brownChoosing Between del and pop()
Use del when the key is known to exist and you do not need its old value. Use pop() when you need that value or when a default makes missing-key handling simpler.
Verify the Key Is No Longer Accessible
After deletion, the key is no longer in the dictionary:
account = {'username': 'sam', 'active': True}
del account['active']
print('active' in account) # FalseTrying to access the removed key with square brackets also raises KeyError:
print(account['active']) # KeyError: 'active'For safe access when a key may be absent, use get() with an optional default:
status = account.get('active', False)
print(status) # FalseThe get() method reads a value safely; it does not remove the key.
Common Problems and Troubleshooting
A KeyError Occurs During Deletion
The requested key is not present, or its spelling and capitalization differ from the actual key. Inspect the dictionary and its keys:
print(person)
print(person.keys())Then use the exact key, check membership before using del, or use pop(key, default) when an absent key is expected.
The Dictionary Still Contains the Item
Deletion may have been applied to a different dictionary variable, the key may not match the expected key, or the output may have been checked before deletion. Print the same variable immediately after the statement:
data = {'color': 'blue', 'size': 'large'}
del data['size']
print(data) # {'color': 'blue'}Verify both the dictionary variable name and the exact key name.
The Removed Value Is Needed Later
del does not return the deleted value. Replace it with pop() and store the result:
height = person.pop('height', None)
if height is not None:
print('Removed height:', height)Key Points
- A dictionary stores values under unique keys.
- Deleting an item removes both its key and its associated value.
del dictionary[key]changes the original dictionary in place and returns nothing.delraisesKeyErrorwhen the key is missing.- Use
if key in dictionaryto check before deleting. dict.pop(key)removes an item and returns its previous value.dict.pop(key, default)safely handles a potentially absent key.- After deletion, square-bracket access to the removed key raises
KeyErrorunless safe access such asget()is used.