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

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), ('banana', 3), ('orange', 2), ('pear', 1)])
apple = foo['apple']

How do I get the banana using just foo and apple?


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")
>>> od.next_key("banana")
>>> od.next_key("orange")
>>> od.next_key("pear")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in next_key
ValueError: 'pear' is the last key
>>> od.first_key()

Need Your Help

NullPointerException when loading fragments

android exception android-fragments

I get a NullPointerException when I try to load a fragment.

IDataObject drag/drop issue, casting from __ComObject

c# .net drag-and-drop ipc marshalling

I'm having an issue involving the following scenario, Application A has a DataGridView, from which objects are selected. They are dragged into a DataGridView inside Application B, and the objects ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.