groupby and itemgetter

Roman Bertle bertle at smoerz.org
Fri Oct 6 05:13:36 EDT 2006


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). Why was the, imho, more complicated version used as
example in the documentation?

Regards, Roman



More information about the Python-list mailing list