Python one-liner for counting occurrences of each value in a sequence

Suppose we have a sequence [2,1,1,3,4,4,4,4,4,5,5,2,2,2] and we want to know how many of each value there are, in an easy-to-use dictionary form: {1: 2, 2: 4, 3: 1, 4: 5, 5: 2}.

The simplest way is to use Counter from the collections standard library:

>>> from collections import Counter
>>> Counter([2,1,1,3,4,4,4,4,4,5,5,2,2,2])
Counter({4: 5, 2: 4, 1: 2, 5: 2, 3: 1})

A Counter is dict subclass so, once it's created, you can use it like a dictionary. You can also get a regular dictionary from it with

dict(Counter([2,1,1,3,4,4,4,4,4,5,5,2,2,2]))

[Hat tip to reader qsantos.]

I like the itertools and more-itertools[1] libraries because they contain many quick solutions for working with iterables. itertools is part of the Python standard library; more-itertools isn't, but it's good to look both of them over to know what's available there. For example, the task of counting values can be done using the run_length() function in more-itertools[1], although that method is a little more verbose than the one using Counter:

>>> from more_itertools import run_length
>>> dict(run_length.encode(sorted([2,1,1,3,4,4,4,4,4,5,5,2,2,2])))
{1: 2, 2: 4, 3: 1, 4: 5, 5: 2}

[1] https://pypi.org/project/more-itertools/


August 01, 2023

October 07, 2013

February 02, 2012

June 01, 2011

October 17, 2009

April 10, 2008

July 03, 2004

April 28, 2004

March 18, 2004

March 11, 2004