pythonpython-3.xordereddictionary

How to get last element from OrderedDict (without removing it)


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 also remove the pair from od which I don't want.

Currently I use:

class MyOrderedDict(OrderedDict):

    def last(self):
        return next(reversed(self))

Can/should I do this? What's a good way to access the last element?


Solution

  • Using next(reversed(od)) is a perfect way of accessing the most-recently added element. The class OrderedDict uses a doubly linked list for the dictionary items and implements __reversed__(), so this implementation gives you O(1) access to the desired element. Whether it is worthwhile to subclass OrderedDict() for this simple operation may be questioned, but there's nothing actually wrong with this approach.