Re: Why doesn't collections.Counter support a "key" argument in its constructor?

Random832 random832 at fastmail.com
Sat Sep 12 19:22:29 EDT 2020


On Fri, Sep 11, 2020, at 12:01, Saurav Chirania wrote:
> I really like that python's sort method accepts a key function as a
> parameter which can be used to specify how elements should be compared.
> 
> Similarly, we could have a "key" argument which specifies how elements
> should be counted. Let's say we have a list of a million students. I would
> like to do something like:
> c = Counter(students, key = lambda student: student.marks)
> 
> which would return a Counter which maps marks to the number of students
> with that marks. Let's say 29 students in the list had scored 100 marks, so
> one entry in the counter would be key=100, val=29.
> 
> So, why doesn't Counter's constructor support this argument? Are there
> other pythonic ways to do this?

I'd like to add to this discussion that a feature like this would not be unreasonable to have on all dictionaries, and when I have wanted it in the past it has been on WeakKeyDictionary, for which the obvious workaround of making a wrapper class that uses the key function for __eq__ and __hash__ isn't usable


More information about the Python-list mailing list