42

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?

Acoop
  • 2,586
  • 2
  • 23
  • 39
  • 1
    Read [the docs for `OrderedDict.popitem`](https://docs.python.org/2/library/collections.html#collections.OrderedDict.popitem): *"The pairs are returned in LIFO order if `last` is true or FIFO order if false."* – jonrsharpe Nov 26 '14 at 17:55
  • `dictioary.popitem()` doesn't take an argument, use `dictionary.pop(key)`. – martineau Nov 26 '14 at 17:59
  • @martineau you should also follow that link - `.popitem` *does* take an argument, `last`, otherwise the OP would get a `TypeError` rather than unexpected behaviour – jonrsharpe Nov 26 '14 at 18:12
  • @jonrsharpe: True, `OrderedDict.popitem()` _does_ take an optional argument, but it's not a key in the dictionary -- therefore the OP should use the inherited [`dict.pop(key)`](https://docs.python.org/2/library/stdtypes.html?highlight=pop#dict.pop) method, especially if they want the associated value of the key being removed returned as a result. – martineau Nov 26 '14 at 18:33
  • 3
    Possible duplicate of [Delete an item from a dictionary](https://stackoverflow.com/questions/5844672/delete-an-item-from-a-dictionary) – slm Jul 27 '17 at 17:39

2 Answers2

67

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.

14

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

d = OrderedDict([(1,2),(3,4)])
d.pop(your_key)
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321