Python dictionary allows you to store values as a key-value pair.
You can remove an item from a dictionary using the del yourdict[“key”]
statement in Python.
Basic Example
yourdict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
}
del yourdict["one"]
yourdict
- If the key exists, it’ll delete it. Otherwise, it’ll throw a
keyError
.
Output
{'two': 2, 'three': 3, 'four': 4}
This tutorial teaches you the different methods to remove an item from a dictionary in Python.
Table of Contents
Using Del Statement
The del statement removes an item from the dictionary using the key
.
- If the key is available, then the item will be deleted
- If the key is NOT available, a
KeyError
will be thrown
Code
yourdict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
}
del yourdict["one"]
yourdict
Output
The item with key
one is removed from the dictionary.
{'two': 2, 'three': 3, 'four': 4}
The following code snippet demonstrates the KeyError
when you attempt to delete an item that is not available in the dictionary.
To avoid this error while using the del
statement, you need to check if a key exists in a dictionary before attempting to delete it.
yourdict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
}
del yourdict["onee"]
yourdict
Output
---------------------------------------------------------------------------
KeyError
/var/folders/gb/19ly8vfs7t53plwx43wx1q3m0000gn/T/ipykernel_45472/1409174214.py in <module>
----> 9 del yourdict["onee"]
11 yourdict
KeyError: 'onee'
This is the usage and caveats of the del
statement while using it to delete an element from the dictionary.
Using Pop
The pop method removes the item from the dictionary and returns the value of the removed item.
You can use this method when you want to use the value of the deleted item.
Parameters
Key
– Key of the item to be deletedOptional value
– Optional – A value that needs to be returned when the key is unavailable instead of throwing a key error. If this parameter is not passed,KeyError
will be thrown when the key is unavailable.
Code
yourdict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
}
yourdict.pop("one")
Output
The item with key one is deleted, and the value of the item 1 is returned.
1
The code below demonstrates how to use the optional parameter to return a default value instead of throwing a keyerror
when the key
is unavailable in the dictionary.
yourdict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
}
yourdict.pop("onee", "Key not found to delete")
Output
The key onee is not available in the dictionary. Hence the optional value is returned instead of throwing a KeyError
.
'Key not found to delete’
Using PopItem
The popitem()
method removes the last item from the dictionary.
Use this method when you know the key of the item that needs to be removed.
In Python versions before 3.7, a random item is removed instead of removing the last item.
Code
yourdict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
}
yourdict.popitem()
Output
The last item is removed from the dictionary, and both the keys and values are returned.
('four', 4)
Remove Multiple Keys From Dictionary
There is no method directly available to delete multiple keys from a dictionary.
To remove multiple keys,
- Add the multiple keys to a
tuple
, alist
, or aset
and iterate over it. - During each iteration, invoke the
pop()
method to remove the item with thatkey
.
Code
yourdict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
}
keys_to_remove = ('one', 'two')
for key in keys_to_remove:
print(yourdict.pop(key, None))
Output
1
2
Delete All Elements from Dictionary
To delete all elements from a dictionary in Python,
- use the clear() method.
It removes all items from the dictionary, but the dictionary object itself is not removed.
Code
yourdict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
}
yourdict.clear()
yourdict
Output
All the elements from the dictionary are removed, and an empty dictionary object is still available.
{}
Delete Dictionary Key While Iterating
To delete dictionary keys while iterating, you need to iterate the dictionary keys after converting them into a list using list(yourdict.keys())
.
If you iterate directly with dict.keys(), you’ll face a Runtime error. RuntimeError: dictionary changed size during iteration
. This is because when you remove a key, the size of the dictionary will be changed, and the iteration cannot happen.
Code
yourdict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
}
for k in list(yourdict.keys()):
if k == "one":
del yourdict[k]
yourdict
Output
The key one is removed from the dictionary while iterating over it.
{'two': 2, 'three': 3, 'four': 4}
Pop Vs Del
Pop | Del |
---|---|
Returns the value of the deleted key | Returns nothing after deleting the key |
Supports an additional parameter that can be used to return a value when the key is unavailable in the dictionary. | Doesn’t support an additional parameter to pass a return a value when the key is unavailable |
Returns KeyError when the key is unavailable | Returns KeyError when the key is unavailable |