Last element in OrderedDict

前端 未结 4 1511
野趣味
野趣味 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:51

    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()))
    

提交回复
热议问题