Last element in OrderedDict

前端 未结 4 1504
野趣味
野趣味 2021-02-01 00:51

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

4条回答
  •  -上瘾入骨i
    2021-02-01 01:34

    A little magic from timeit can help here...

    from collections import OrderedDict
    class 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 out
    
    class 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.159217119216919
    OrderedDict2 3.3667118549346924
    OrderedDict3 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.

提交回复
热议问题