Skip to main content

You can remove dictionary items in several ways:


The pop() Method

Give pop() a key name and it takes that item out of the dictionary:

Example

Prompt
Write a Python program that creates a dictionary called thisdict with keys "brand", "model", and "year" with values "Ford", "Mustang", and 1964. Then remove the "model" key using the pop() method and print the dictionary.
Output: complete Python program

The popitem() Method

With popitem(), the item inserted most recently is the one to go (before version 3.7, the choice was random):

Example

Prompt
Write a Python program that creates a dictionary called thisdict with keys "brand", "model", and "year" with values "Ford", "Mustang", and 1964. Then remove the last inserted item using the popitem() method and print the dictionary.
Output: complete Python program

The del Keyword

Follow the del keyword with a key name to delete that item:

Example

Prompt
Write a Python program that creates a dictionary called thisdict with keys "brand", "model", and "year" with values "Ford", "Mustang", and 1964. Then remove the "model" key using the del keyword and print the dictionary.
Output: complete Python program

Example

On its own, del wipes out the whole dictionary:

Prompt
Write a Python program that creates a dictionary called thisdict with keys "brand", "model", and "year" with values "Ford", "Mustang", and 1964. Then delete the entire dictionary using the del keyword and try to print it, which will cause an error because thisdict no longer exists.
Output: complete Python program

The clear() Method

Calling clear() leaves the dictionary empty:

Example

Prompt
Write a Python program that creates a dictionary called thisdict with keys "brand", "model", and "year" with values "Ford", "Mustang", and 1964. Then empty the dictionary using the clear() method and print it.
Output: complete Python program