bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/Python/Foundations Practice
Python•Foundations Practice

Python - Remove Dictionary Items

Concept visual

Python - Remove Dictionary Items

keys map to buckets01kiwi:12pear:43apple:7grape:9

Removing Items

There are several methods to remove items from a dictionary:

Example

The pop()

method removes the item with the specified key name:

thisdict =  {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)

Example

The popitem()

method removes the last inserted item (in versions before 3.7, a random item is removed instead):

thisdict =  {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)

Example

The del keyword removes the item with the specified key name:

thisdict =  {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)

Example

The del keyword can also delete the dictionary completely:

thisdict =  {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict print(thisdict) #this will cause an error because "thisdict"

no longer exists.

Example

The clear()

method empties the dictionary:

thisdict =  {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)

Previous

Python - Add Dictionary Items

Next

Python - Nested Dictionaries