Dictionaries in Python are used to store information that comes in key-value pairs. A dictionary contains a key and its value.
Each country ( key) has its capital (value), and in this context, the different countries can be a key, whereas their respective capitals are their values.
Let’s take a look at the code below:
countries={‘Ghana’: ’Accra’}
print(countries)
We create a dictionary named countries, where Ghana is the key, and Accra is the value.
{'Ghana': 'Accra'}
The code returns a dictionary as expected.
We can use the following methods to remove items from a dictionary in Python:
del keywordclear() methodpop() methodpopitem() methoddel keywordThe del keyword method uses the keyword from the dictionary to remove an item.
countries={"Ghana": "Accra", "China": "Beijing"}# using the del keyworddel countries["China"]print(countries)
clear() methodThe clear() method clears all the items in the dictionary.
countries={"Ghana": "Accra", "China": "Beijing"}# using the clear() methodcountries.clear()print(countries)
pop() methodThe pop method uses the keyword from the given dictionary to remove an item from that dictionary. The pop method is similar to the del keyword method because they both use the keyword from the dictionary.
countries={"Ghana": "Accra", "China": "Beijing"}# using the pop() methodcountries.pop("China")print(countries)
popitem() methodThe popitem() removes the last item added to the dictionary.
countries={"Ghana": "Accra", "China": "Beijing"}# using the clear() methodcountries.popitem()print(countries)
Free Resources