[Python-Dev] Candidate Itertools

Raymond Hettinger python at rcn.com
Sat Jun 19 16:30:30 EDT 2004

> > Feedback is requested for two prospective itertools:
> >
> > def count_elements(iterable):
> >     b = {}
> >     for elem in iterable:
> >         b[elem] = b.get(elem, 0) + 1
> >     return ((cnt, elem) for elem, cnt in b.iteritems())
> +1 provided it returns either (elem, cnt) or the dict itself.

Hmm, there seems to be 100% support for returning a dictionary and zero
support for my iterable (cnt, elem) ... to feed min(), max(), sorted(),
nlargest(), and nsmallest().

If a dictionary is returned, it no longer makes sense to put this in
itertools.  It looks like what is being requested is an alternate
dictionary constructor classmethod, dict.countkeys(iterable).

To get what I was after now takes more intermediate steps:

  nlargest((c,e) for (e,c) in dict.countkey(iterable).iteritems())

It gets the job done, but lacks the grace of:


Are you guys sure you would prefer having the dict instead of the
pairswapped iterable?

Raymond Hettinger

More information about the Python-Dev mailing list