Fwd: Python one-liner?

Karl Knechtel zahlman at gmail.com
Mon Apr 16 17:18:40 EDT 2012


On Sat, Apr 14, 2012 at 7:26 AM, Tim Chase
<python.list at tim.thechases.com> wrote:
>
> On 04/13/12 22:54, Chris Angelico wrote:
>>
>> Yes, that would be the right method to use. I'd not bother with the
>> function and map() though, and simply iterate:
>>
>> d = {}
>> for val in l:
>>  d.setdefault(f(val), []).append(val)
>
>
> Or make d a defaultdict:
>
>  from collections import defaultdict
>  d = defaultdict(list)
>  for val in l:
>    d[f(val)].append(val)


For those insisting on getting something functional-ish:

d = {k: list(v) for k, v in itertools.groupby(sorted(l, key=f), f)}

(and one of these days I will send to the list instead of directly
replying, the first time...)

--
~Zahlman {:>



More information about the Python-list mailing list