Last element in OrderedDict

前端 未结 4 1546
野趣味
野趣味 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条回答
  •  甜味超标
    2021-02-01 01:34

    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.

提交回复
热议问题