How do I iterate over items in a dict grouped by N number of elements?

Arnaud Delobelle arnodel at googlemail.com
Fri Mar 14 08:17:23 EDT 2008


On Mar 14, 1:34 am, Noah <n... at noah.org> wrote:
> What is the fastest way to select N items at a time from a dictionary?
> I'm iterating over a dictionary of many thousands of items.
> I want to operate on only 100 items at a time.
> I want to avoid copying items using any sort of slicing.
> Does itertools copy items?
>
> This works, but is ugly:
>
> >>> from itertools import *
> >>> D = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':10}
> >>> N = 3
> >>> for G in izip(*[chain(D.items(), repeat(None, N-1))]*N):

This solution matches exactly the one proposed in itertools.  The
following is an extract from http://docs.python.org/lib/itertools-functions.html.

Note, the left-to-right evaluation order of the iterables is
guaranteed. This makes possible an idiom for clustering a data series
into n-length groups using "izip(*[iter(s)]*n)". For data that doesn't
fit n-length groups exactly, the last tuple can be pre-padded with
fill values using "izip(*[chain(s, [None]*(n-1))]*n)".

--
Arnaud



More information about the Python-list mailing list