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?
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?
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)