On May 9, 10:10 am, [EMAIL PROTECTED] wrote: > Hello all, > > I have a dictionary of which i'm itervalues'ing through, and i'll be > performing some logic on a particular iteration when a condition is > met with trusty .startswith('foo'). I need to grab the previous > iteration if this condition is met. I can do something with an extra > var to hold every iteration while iterating, but this is hacky and not > elegant.
Often when you're iterating, 'hacky' code can be lifted out into a separate generator, keeping the details of the hacks nicely away from your code. That's true here... def iterprevious(seq): """Generate pairs of (previous element, current element) from seq.""" last = None for x in iter(seq): yield last, x last = x Then, when you want use it... for previous, (key, value) in iterprevious(d.iteritems()): ... In the loop, previous will either be None if we're on the first element, otherwise (previous_key, previous_value). -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list