Skip to content
Advertisement

Detect last iteration over dictionary.iteritems() in python

Is there a simple way to detect the last iteration while iterating over a dictionary using iteritems()?

Advertisement

Answer

This is a special case of this broader question. My suggestion was to create an enumerate-like generator that returns -1 on the last item:

def annotate(gen):
    prev_i, prev_val = 0, gen.next()
    for i, val in enumerate(gen, start=1):
        yield prev_i, prev_val
        prev_i, prev_val = i, val
    yield '-1', prev_val

Add gen = iter(gen) if you want it to handle sequences as well as generators.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement