Grabbing previous iteration in a dict

dannywebster at googlemail.com dannywebster at googlemail.com
Fri May 9 11:44:49 EDT 2008


On May 9, 4:09 pm, Paul Hankin <paul.han... at gmail.com> wrote:
> 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


Hi all - some good stuff here.  Thanks for the info, I have a few
ideas
to play with.

thanks again

dan.




More information about the Python-list mailing list