groupby and itemgetter

Steven Bethard steven.bethard at gmail.com
Fri Oct 6 11:15:23 EDT 2006


Roman Bertle wrote:
> Hello,
> 
> there is an example how to use groupby in the itertools documentation
> (http://docs.python.org/lib/itertools-example.html):
> 
> # Show a dictionary sorted and grouped by value
>>>> from operator import itemgetter
>>>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
>>>> di = sorted(d.iteritems(), key=itemgetter(1))
>>>> for k, g in groupby(di, key=itemgetter(1)):
> ...     print k, map(itemgetter(0), g)
> ...
> 1 ['a', 'c', 'e']
> 2 ['b', 'd', 'f']
> 3 ['g']
> 
> Now i wonder why itemgetter is used in this example. More
> straightforward is:
> 
>>>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
>>>> di = sorted(d.iterkeys(), key=d.get)
>>>> for k, g in groupby(di, key=d.get):
> ...     print k, list(g)
> ...
> 1 ['a', 'c', 'e']
> 2 ['b', 'd', 'f']
> 3 ['g']
> 
> This code does not need the operator module, and its also faster (tested
> using timeit).

It looks like it's even faster if you drop the iterkeys() call and just 
write:

     di = sorted(d, key=d.get)

As to why itemgetter is used, I don't really know...

STeVe



More information about the Python-list mailing list