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.
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 key
next(iter(od))
# Get last key
next(reversed(od))
# Get first value
od[next(iter(od))]
# Get last value
od[next(reversed(od))]
# Get first key-value tuple
next(iter(od.items()))
# Get last key-value tuple
next(reversed(od.items()))