You can remove an item from the dictionary using the pop() function with the key name.
company_dictionary = {
"name": "Google",
"country": "USA",
"start_year": 1995
}
company_dictionary.pop("country")
print(company_dictionary)
{'name': 'Google', 'start_year': 1995}
In the above example, the country item was removed from the company_dictionary using the pop() function, so you can see that the country item is missing from the company_dictionary.
You can remove the last item from the dictionary using the popitem() function.
company_dictionary = {
"name": "Google",
"country": "USA",
"start_year": 1995
}
company_dictionary.popitem()
print(company_dictionary)
{'name': 'Google', 'country': 'USA'}
Here, we removed the last item from the company_dictionary using the popitem() function, so as in the output, you can see the start_year item is missing from the company_dictionary because the start_year was the last item from the company_dictionary.
Use the del keyword with a key to remove a specific item from the dictionary.
company_dictionary = {
"name": "Google",
"country": "USA",
"start_year": 1995
}
del company_dictionary["country"]
print(company_dictionary)
{'name': 'Google', 'start_year': 1995}
Using the del keyword, we removed the country item from a company_dictionary, so as you can see, no country item is output.
You can delete the entire dictionary by using the del keyword.
company_dictionary = {
"name": "Google",
"country": "USA",
"start_year": 1995
}
del company_dictionary
print(company_dictionary)
NameError: name 'company_dictionary' is not defined
We removed the entire dictionary using the del keyword. You can see the output "NameError: name 'company_dictionary' is not defined".
Use the clear() function to empty the dictionary. It will delete all items from the dictionary, but the dictionary will still exist.
company_dictionary = {
"name": "Google",
"country": "USA",
"start_year": 1995
}
company_dictionary.clear()
print(company_dictionary)
{}
Using the clear() function, we removed all items from the dictionary. In the output, you can see that the curly brackets ({}) are empty.