Search code examples
pythondictionaryordereddictionary

Delete a key and value from an OrderedDict


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?


Solution

  • 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.