Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 374
John Mee Avatar asked Sep 08 '12 05:09

John Mee


People also ask

How do you slice in OrderedDict?

You can use the itertools. islice function, which takes an iterable and outputs the stop first elements. This is beneficial since iterables don't support the common slicing method, and you won't need to create the whole items list from the OrderedDict.

Is OrderedDict sorted?

You'll have to create a new one since OrderedDict is sorted by insertion order.

What is difference between dict and OrderedDict Python?

The OrderedDict is a subclass of dict object in Python. The only difference between OrderedDict and dict is that, in OrderedDict, it maintains the orders of keys as inserted. In the dict, the ordering may or may not be happen. The OrderedDict is a standard library class, which is located in the collections module.

What is collections OrderedDict?

An OrderedDict is a dictionary that remembers the order of the keys that were inserted first. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Example.


1 Answers

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
like image 60
ChrisRob Avatar answered Oct 21 '22 03:10

ChrisRob