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

Paul Rubin http
Thu Mar 13 22:02:24 EDT 2008


Noah <noah at noah.org> writes:
> 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.

I'd do something like (untested):

    def groups(seq, n):
      while True:
        s = list(itertools.islice(seq, n))
        if not s: return
        yield s

   items = d.iteritems()
   for g in groups(items, 100):
     operate_on (g)

> Does itertools copy items?

I don't understand this question.



More information about the Python-list mailing list