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
?
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.
You'll have to create a new one since OrderedDict is sorted by insertion order.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With