Search code examples
python-3.xdictionarycollectionsordereddict

Pop element at the beginning or at the last from dict in python3


Collection module in python has a datatype OrderedDict(), which enables us to save the key value pairs in the same order as they were inserted in dict. It has a method popitem, which allows us to pop items at the beginning or at the last

dict.popitem(last = True)
dict.popitem(last = False)

The default dict in python 3 also works as OrderedDict(), i.e., it maintains the order of key value pairs as they were inserted. But how to remove the first or the last element from this dict as in OrderedDict(), without using the traditional for loop for accessing the key value pair as

for key, value in dict:
    dict.pop(key)
    break

I just want to know if there is any inbuild function for popping the first or the last element in default dict of python 3 as in OrderedDict(). I searched but couldn't find any.


Solution

  • Since Python 3.6, dict.popitem always acts as a LIFO like OrderedDict.popitem(last=True) does.

    But while there is no direct support from dict to make the popitem method pop from the front of the dict, you can simulate the FIFO behavior of OrderedDict.popitem(last=False) such as:

    d = OrderedDict(a=1, b=2)
    k, v = d.popitem(last=False) # k = 'a', v = 1
    

    by getting the first key of the dict and then popping that key for its value:

    d = {'a': 1, 'b': 2}
    k = next(iter(d)) # k = 'a'
    v = d.pop(k) # v = 1