Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How to remove items from a dictionary in Python

Onyejiaku Theophilus Chidalu

Overview

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

Code example

For example, each country (this is a key) has its capital (this is the value), and in this context, the different countries can be a key, whereas their respective capitals are their values.

Take a look at the code below:

countries={‘Ghana’: ’Accra’}
print(countries)

Code explanation

We create a dictionary named countries, where USA is the key, and Washington is the value.

Code output

{'Ghana': 'Accra'}

The code returns a dictionary as expected.

How to remove items from a dictionary

You 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 helps clear 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 in that 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() method is used to remove the last item added to the dictionary.

Example

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

RELATED TAGS

python
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring