Last element in OrderedDict

max picture max · Mar 29, 2012 · Viewed 27.6k times · Source

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.

What's a good way to do that? Can /should I do this:

class MyOrderedDict(OrderedDict):
  def last(self):
    return next(reversed(self))

Answer

Sven Marnach picture Sven Marnach · Mar 29, 2012

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.