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

Saurav Chirania chirania.saurav at gmail.com
Fri Sep 11 12:01:27 EDT 2020


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?

Regards,
Saurav Chirania


More information about the Python-list mailing list