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

后端 未结 4 872
野的像风
野的像风 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条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-08 02:28

    I shudder to think how slow this will be on a list of size, but the only way I've come up with so far...

    >>> foo.items()[foo.keys().index('apple') + 1]
    ('banana', 3)
    

    Edit:

    The example was slightly contrived; my actual collection is keyed by dates. If I need the entry after today; found a solution using dropwhile...

    >>> foo = OrderedDict([(datetime.date(2000,1,1), 4), (datetime.date(2000,5,23), 3), datetime.date(2000,10,1), 2), (datetime.date(2000,12,31), 1)])
    >>> today = datetime.date(2000,1,30)
    >>> foo.items()[foo.keys().index((itertools.dropwhile(lambda d: d

    Quite a mouthful.

提交回复
热议问题