I have od
of type OrderedDict
. I want to access its most recently added (key, value) pair. od.popitem(last = True)
would do it, but would
Your idea is fine, however the default iterator is only over the keys, so your example will only return the last key. What you actually want is:
class MyOrderedDict(OrderedDict):
def last(self):
return list(self.items())[-1]
This gives the (key, value)
pairs, not just the keys, as you wanted.
Note that on pre-3.x versions of Python, OrderedDict.items()
returns a list, so you don't need the list()
call, but later versions return a dictionary view object, so you will.
Edit: As noted in the comments, the quicker operation is to do:
class MyOrderedDict(OrderedDict):
def last(self):
key = next(reversed(self))
return (key, self[key])
Although I must admit I do find this uglier in the code (I never liked getting the key then doing x[key]
to get the value separately, I prefer getting the (key, value)
tuple) - depending on the importance of speed and your preferences, you may wish to pick the former option.