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
main.py
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
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
main.py
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
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
main.py
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
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
main.py
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.
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
main.py
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)