pythonpython-2.7python-2.5

Skip statements in case of last item in iterator


I want to skip a number of statements in a for-loop for the last key, value pair in a dict.

Let's assume the next snippet to be the real program:

a = { 'a': 1, 'b': 2, 'c': 3 } # I don't know the exact values, so can't test on them
for key, value in a.iteritems():
    # statements always to be performed

    # statements I want to skip when the current key, value pair is the last unprocessed pair in the dict.

    # maybe some more statements not to be skipped (currently not forseen, but might be added in the future)

# other statements in the program

It is probably something simple, but I can't find it.

OK, I could write it using a while-loop:

stop = False
b = a.iteritems()
next_key, next_value = b.next()
while True:
    key, value = next_key, next_value
    # do stuff which should be done always

    try:
        next_key, next_value = b.next()
    except StopIteration:
        stop = True
    else:
        # do stuff which should be done for everything but the last pair

    # the future stuff which is not yet forseen.

    if stop:
        break

But I think this is ugly code, hence I look for a nice way to do it in a for-loop. Is this possible?

Oh yes: It needs to work for python 2.7 (and python 2.5 would be a bonus ) since that are the python versions at my work (mainly python 2.7).


Solution

  • You can use itertools.islice to take all items except the last:

    from itertools import islice
    
    a = { 'a': 1, 'b': 2, 'c': 3 }
    for key, value in islice(a.iteritems(), len(a)-1 if a else None):
        ...
    

    The ternary conditional helps to handle cases where len(a)-1 gives a negative result i.e. dict is empty.