[Python-ideas] grouping / dict of lists

Michael Selik mike at selik.org
Mon Jul 2 12:39:00 EDT 2018


>
> On Mon, Jul 2, 2018 at 2:32 AM Nicolas Rolin <nicolas.rolin at tiime.fr>
>> wrote:
>>
>>> For example the default could be such that grouping unpack tuples (key,
>>> value) from the iterator and do what's expected with it (group value by
>>> key). It is quite reasonable, and you have one example with (key, value) in
>>> your example, and no example with the current default.
>>>
>>
On Mon, Jul 2, 2018 at 3:22 AM Nicolas Rolin <nicolas.rolin at tiime.fr> wrote:

> My question would be: does it have to be a key function? Can't we just
> remove the "key" argument?
>

In the examples or from the parameters? A key function is necessary to
support a wide variety of uses.


Because for pretty much all the given examples, I would find my default as
> readable and nearly as short as the "key" syntax :
>
> > grouping(words, key=len)
> grouping((len(word), word for word in words))
>

I think the fact that you misplaced a closing parenthesis demonstrates how
the key-function pattern can be more clear.


The code is slightly more verbose, but it is akin to filter(iterable,
> function) vs (i for i in iterable if function(i)).
>

Sometimes I prefer ``map`` and sometimes I prefer a list comprehension. It
usually hinges on whether I think the reader might get confused over what
one of the elements is. If so, I like to write out the comprehension to
provide that extra variable name for clarity.

I'd write:
    map(len, words)

But I'd also write
    [len(fullname) for fullname in contacts]

I appreciate that defaulting the grouping key-function to ``itemgetter(0)``
would enable a pleasant flexibility for people to make that same choice for
each use. I haven't fully come around to that, yet, because so many other
tools use the equality function as the default.



On Mon, Jul 2, 2018 at 3:48 AM Steven D'Aprano <steve at pearwood.info> wrote:

> On Mon, Jul 02, 2018 at 02:52:03AM -0700, Michael Selik wrote:
> > Third, some classes might have a rich equality method that allows many
> > interesting values to all wind up in the same group even if using the
> > default "identity" key-function.
>
> I would expect an identity key function to group by *identity* (is), not
> equality. But I would expect the default grouper to group by *equality*.


Yep, I should have been saying "equality function" instead of "identity
function." Thanks for the clarification.

>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180702/6f6f5950/attachment.html>


More information about the Python-ideas mailing list