Delete a key and value from an OrderedDict

Question:

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?

Asked By: Acoop

||

Answers:

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.

Answered By: user2555451

You can use pop, popitem removes the last by default:

d = OrderedDict([(1,2),(3,4)])
d.pop(your_key)
Answered By: Padraic Cunningham