Delete a key and value from an OrderedDict

Acoop picture Acoop · Nov 26, 2014 · Viewed 45.8k times · Source

I am trying to remove a key and value from an OrderedDict but when I use:

dictionary.popitem(key)

it removes the last key and value even when a different key is supplied. Is it possible to remove a key in the middle if the dictionary?

Answer

user2555451 picture user2555451 · Nov 26, 2014

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.