Pop the first inserted key-value pair in a dictionary [Python 3.7+]

Viewed 35

Suppose I have a dictionary in python 3.9:

dictionary = {
    'a': 2,
    'b': 3,
    'c': 4
}

If I use dictionary.popitem(), it pops and returns ('c', 4).
Is there any way to retrieve ('a', 2), i.e the first item, in O(1) time?

1 Answers

I don't think there is a builtin way to achieve this, but you can write a short function:

def popfirst(d):
    k = next(iter(d))    # get the first key
    return (k, d.pop(k)) # pop based on the key

popfirst(dictionary)

output: ('a', 2)

Related