Is it possible to get the next iteritem in a for loop where you loop is
for x,y dict.iteritems()
where I'm interested in the next item of x without moving the iterator forward.
In Python 2.7.x
Is it possible to get the next iteritem in a for loop where you loop is
for x,y dict.iteritems()
where I'm interested in the next item of x without moving the iterator forward.
In Python 2.7.x
This is more or less a duplicate of the questions How to access previous/next element while for looping? and Iterate a list as pair (current, next) in Python .
Note that what follows is solely an adaption of the most upvoted answer in the first thread, adapted to fit your specification:
def iterate(iterable):
iterator = iter(iterable)
item = iterator.next()
for next_item in iterator:
yield item, next_item
item = next_item
yield item, None
Usage:
d = {'a': 1, 'b': 2, 'c': 3}
for item, next_item in iterate(d.iteritems()):
print item, '| next:', next_item
Credit due to Markus Jarderot for the solution.