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

后端 未结 4 924
野的像风
野的像风 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:47

    If you are OK with accessing those parts of the OrderedDict implementation that are intentionally kept private:

    >>> class MyOrderedDict(OrderedDict):
    ...     def next_key(self, key):
    ...             next = self._OrderedDict__map[key][1]
    ...             if next is self._OrderedDict__root:
    ...                     raise ValueError("{!r} is the last key".format(key))
    ...             return next[2]
    ...     def first_key(self):
    ...             for key in self: return key
    ...             raise ValueError("OrderedDict() is empty")
    ... 
    >>> od = MyOrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
    >>> od.next_key("apple")
    'banana'
    >>> od.next_key("banana")
    'orange'
    >>> od.next_key("orange")
    'pear'
    >>> od.next_key("pear")
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 5, in next_key
    ValueError: 'pear' is the last key
    >>> od.first_key()
    'apple'
    

提交回复
热议问题