1

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

user123577
  • 121
  • 2
  • 12
  • 1
    possible duplicate of [How to access previous/next element while for looping?](http://stackoverflow.com/questions/323750/how-to-access-previous-next-element-while-for-looping) – Tim Jun 19 '14 at 14:26

1 Answers1

5

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.

Community
  • 1
  • 1
imolit
  • 7,743
  • 3
  • 25
  • 29