Python one-liner?

Ian Kelly ian.g.kelly at gmail.com
Mon Apr 16 18:04:04 EDT 2012


On Mon, Apr 16, 2012 at 3:18 PM, Karl Knechtel <zahlman at gmail.com> wrote:
> d = {k: list(v) for k, v in itertools.groupby(sorted(l, key=f), f)}

Note that the sorted call would fail if f returns objects of unorderable types:

Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> f = lambda x: x
>>> l = [object(), object()]
>>> import itertools
>>> d = {k: list(v) for k, v in itertools.groupby(sorted(l, key=f), f)}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: object() < object()

Which is unfortunate since grouping in general should not need to
depend on orderability.



More information about the Python-list mailing list