In this article, we would cover how to delete items from a dictionary. We have already covered Dictionaries in Python here. We store data in Dictionaries in the form of key:value pairs, which are called items. Comma (,) separates every item in a dictionary. Furthermore, a dictionary is enclosed in curly brackets {}.
We discuss four methods here to delete items from a dictionary –
- popitem() method,
- pop() method,
- del keyword and,
- clear() method.
We cover each of these methods in next section with relevant examples.
Delete items from a dictionary
Method I. popitem() method – It deletes last item from a dictionary. Let’s say we have a dictionary, d –
d=dict(name="abc", age=24, address="xyz, qwerty")
Here, the last key:value pair or item is address:”xyz, qwerty” will be deleted if we use popitem() method. To remove the last item from a dictionary, use the following code –
d.popitem()
It shows us the removed item –
('address', 'xyz, qwerty')
To check for the item –
print(d)
It would return with –
{'name': 'abc', 'age': 24}
We now turn our attention towards pop() method next.
Method II. If we want to delete an item using a specific key name. Then, we use pop() method. Continuing with the above example of dictionary, d –
d=dict(name="abc", age=24, address="xyz, qwerty")
To delete the item associated with key “name”, use the following code –
d.pop("name")
It would show us the value which it acted on.
'abc'
To see the outcome –
print(d)
It returns with –
{'age': 24, 'address': 'xyz, qwerty'}
Method III. del keyword – It can either be used to remove an item from a dictionary or we can delete the entire dictionary itself.
d=dict(name="abc", age=24, address="xyz, qwerty")
To delete the item with key – “age”
del d["age"]
Next, use print() method to check for the updated dictionary, d –
print(d)
It returns with –
{'name': 'abc', 'address': 'xyz, qwerty'}
But, if we want to delete the entire dictionary itself –
del d
If we use print() method now to display the contents of the dictionary it would throw NameError –
NameError: name 'd' is not defined.
Method IV. Lastly, we have clear() method. It clears the content of a dictionary. But, it won’t delete the dictionary itself.
d=dict(name="abc", age=24, address="xyz, qwerty")
To clear the contents of dictionary, d –
d.clear()
To check –
print(d)
It returns with an empty dictionary –
{}
In conclusion, we have covered how to delete items from a dictionary.