Grabbing previous iteration in a dict
Paul Hankin
paul.hankin at gmail.com
Fri May 9 11:09:58 EDT 2008
On May 9, 10:10 am, dannywebs... at googlemail.com 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
More information about the Python-list
mailing list