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:
JavaScript
x
7
1
def annotate(gen):
2
prev_i, prev_val = 0, gen.next()
3
for i, val in enumerate(gen, start=1):
4
yield prev_i, prev_val
5
prev_i, prev_val = i, val
6
yield '-1', prev_val
7
Add gen = iter(gen)
if you want it to handle sequences as well as generators.