How To Remove Dictionary Items
In python, to remove dictionary items , you have many options to choose the best way that suite you, in this page shows will How to Remove Dictionary Items by using a few methods such as pop(), popitem(), clear(), and del().
- Using Pop() method: This method removes the item with the specified key and returns its value. Removes the key ‘a’ and returns its value. Here the example below:
myDict = {'a': 100, 'b': 200, 'c': 300}
myDictValue = myDict.pop('c')
print(myDictValue)
print(myDict)
# Output: 300
# Output: {'a': 1, 'b':200 }
- Using the
popitem()
method: This method removes and returns an arbitrary item (key, value) pair from the dictionary. It removed the last insert item. It’s useful when you want to remove items but don’t care about the specific key.
myDict = {'a': 100, 'b': 200, 'c': 300}
myDictValue = myDict.popitem()
print(myDictValue)
# Output: {'a': 1, 'b':200 }
- Using the
clear()
method: This method removes all items from the dictionary, leaving it empty.
myDict = {'a': 100, 'b': 200, 'c': 300}
myDict.clear()
print(myDict)
# Output: {}
- Using the
del
(): This method removes a specific key and its associated value from the dictionary.
myDict = {'a': 100, 'b': 200, 'c': 300}
del myDict['a']
print(myDict)
# Output: {'b': 200, 'c': 300}