How to get the “next” item in an OrderedDict?

后端 未结 4 870
野的像风
野的像风 2021-02-08 01:44

I\'m using an OrderedDict to random access a list, but now want the next item in the list from the one that I have:

foo = OrderedDict([(\'apple\', 4         


        
4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-08 02:24

    Python 3.X

    dict.items would return an iterable dict view object rather than a list. We need to wrap the call onto a list in order to make the indexing possible:

    >>> from collections import OrderedDict
    >>> 
    >>> foo = OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
    >>> 
    >>> def next_item(odic, key):
    ...     return list(odic)[list(odic.keys()).index(key) + 1]
    ... 
    >>> next = next_item(foo, 'apple')
    >>> print(next, foo[next])
    banana 3
    

提交回复
热议问题