Because key-value pairs in dictionaries are objects, you can delete them using the “del” keyword. The “del” keyword is used to delete a key that does exist. It raises a KeyError if a key is not present in a dictionary. We use the indexing notation to retrieve the item from the dictionary we want to remove.
Yes, you can use del
:
del dct[key]
Below is a demonstration:
>>> from collections import OrderedDict
>>> dct = OrderedDict()
>>> dct['a'] = 1
>>> dct['b'] = 2
>>> dct['c'] = 3
>>> dct
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
>>> del dct['b']
>>> dct
OrderedDict([('a', 1), ('c', 3)])
>>>
In fact, you should always use del
to remove an item from a dictionary. dict.pop
and dict.popitem
are used to remove an item and return the removed item so that it can be saved for later. If you do not need to save it however, then using these methods is less efficient.
You can use pop, popitem removes the last by default:
d = OrderedDict([(1,2),(3,4)])
d.pop(your_key)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With