Last element in OrderedDict Last element in OrderedDict python-3.x python-3.x

Last element in OrderedDict


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.


A little magic from timeit can help here...

from collections import OrderedDictclass MyOrderedDict1(OrderedDict):  def last(self):    k=next(reversed(self))    return (k,self[k])class MyOrderedDict2(OrderedDict):  def last(self):     out=self.popitem()     self[out[0]]=out[1]     return outclass MyOrderedDict3(OrderedDict):  def last(self):     k=(list(self.keys()))[-1]     return (k,self[k])if __name__ == "__main__":  from timeit import Timer  N=100  d1=MyOrderedDict1()  for i in range(N): d1[i]=i  print ("d1",d1.last())  d2=MyOrderedDict2()  for i in range(N): d2[i]=i  print ("d2",d2.last())  d3=MyOrderedDict3()  for i in range(N): d3[i]=i  print("d3",d3.last())  t=Timer("d1.last()",'from __main__ import d1')  print ("OrderedDict1",t.timeit())  t=Timer("d2.last()",'from __main__ import d2')  print ("OrderedDict2",t.timeit())  t=Timer("d3.last()",'from __main__ import d3')  print ("OrderedDict3",t.timeit())

results in:

d1 (99, 99)d2 (99, 99)d3 (99, 99)OrderedDict1 1.159217119216919OrderedDict2 3.3667118549346924OrderedDict3 24.030261993408203

(Tested on python3.2, Ubuntu Linux).

As pointed out by @SvenMarnach, the method you described is quite efficient compared to the other two ways I could cook up.


God, I wish this was all built-in functionality...

Here's something to save you precious time. Tested in Python 3.7. od is your OrderedDict.

# Get first keynext(iter(od))# Get last keynext(reversed(od))# Get first valueod[next(iter(od))]# Get last valueod[next(reversed(od))]# Get first key-value tuplenext(iter(od.items()))# Get last key-value tuplenext(reversed(od.items()))