How to remove items from a dictionary in Python

Dictionaries in Python are used to store information that comes in key-value pairs. A dictionary contains a key and its value.

Example

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)

Code explanation

We create a dictionary named countries, where Ghana is the key, and Accra is the value.

Code output

{'Ghana': 'Accra'}

The code returns a dictionary as expected.

How to remove items from a dictionary

We can use the following methods to remove items from a dictionary in Python:

  • The del keyword
  • The clear() method
  • The pop() method
  • The popitem() method

The del keyword

The del keyword method uses the keyword from the dictionary to remove an item.

Example

countries={"Ghana": "Accra", "China": "Beijing"}
# using the del keyword
del countries["China"]
print(countries)

The clear() method

The clear() method clears all the items in the dictionary.

Example

countries={"Ghana": "Accra", "China": "Beijing"}
# using the clear() method
countries.clear()
print(countries)

The pop() method

The 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.

Example

countries={"Ghana": "Accra", "China": "Beijing"}
# using the pop() method
countries.pop("China")
print(countries)

The popitem() method

The popitem() removes the last item added to the dictionary.

Example

countries={"Ghana": "Accra", "China": "Beijing"}
# using the clear() method
countries.popitem()
print(countries)
Copyright ©2024 Educative, Inc. All rights reserved