Skip to content
Home » The Counter Class from the collections Module

The Counter Class from the collections Module

Spread the love

Today we’ll be talking about the Counter class from the collections module. The Counter class is used to create an object that can be easily converted to a dictionary.

The class counts the occurrences of identical items in a list and sorts them from greatest to least. We get unique items as keys and the numbers of their occurrences as values.

counter class

Create a Counter Class Object

First let’s import the Counter class from the collections module:

>>> from collections import Counter

Let’s create a list of names:

>>> names = ['Joe', 'Mary', 'Luke', 'Mary', 'Mary', 'Steve', 'Joe', 'Mary', 'Luke']

Let’s create a Counter object from the list we just created:

>>> stats = Counter(names)

Now we can view the counter object. It’s very much like a dictionary…

>>> stats
Counter({'Mary': 4, 'Joe': 2, 'Luke': 2, 'Steve': 1})

… but actually it’s a Counter object:

>>> type(stats)
<class 'collections.Counter'>

You can check how many times a particular item occurs in the list. To do so, you just have to use the Counter object with the key:

>>> m = stats['Mary']
>>> m
4

If an element doesn’t occur in the list, you don’t get an error. Instead you get the actual number of occurrences:

>>> b = stats['Betty']
>>> b
0

Change the Number of Occurrences

You can manually change the number of occurrences. Let’s say we want the name Joe to occur 5 times instead of 2:

>>> stats['Joe'] = 5

Now the name indeed occurs 5 times:

>>> stats
Counter({'Joe': 5, 'Mary': 4, 'Luke': 2, 'Steve': 1})

If you set the number of occurrences to 0, the item will still be contained in the Counter object:

>>> stats['Steve'] = 0
>>> stats
Counter({'Joe': 5, 'Mary': 4, 'Luke': 2, 'Steve': 0})

If you don’t need it anymore, you can delete it using the del statement:

>>> del stats['Steve']
>>> stats
Counter({'Joe': 5, 'Mary': 4, 'Luke': 2})

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Convert a Counter Class Object to a List

You can convert the Counter object to a list using the elements method. The elements will be sorted by the number of occurrences from greatest to least:

>>> updated_names = list(stats.elements())
>>> updated_names
['Joe', 'Joe', 'Joe', 'Joe', 'Joe', 'Mary', 'Mary', 'Mary', 'Mary', 'Luke', 'Luke']

Find the Most Common Elements

Using the most_common function you can find the elements that occur the most. You can specify how many elements you need. Let’s find the 2 most popular names:

>>> top2names = stats.most_common(2)
>>> top2names
[('Joe', 5), ('Mary', 4)]

So, you get a list of 2-tuples. Let’s now find the most popular name:

>>> top_name = stats.most_common(1)
>>> top_name
[('Joe', 5)]

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Add and Subtract Counter Objects

Let’s create another list and create a Counter object from it:

>>> german_names = ['Dieter', 'Hans', 'Ilse', 'Hans', 'Ilse', 'Ilse']
>>> stats_de = Counter(german_names)

You can add Counter objects. Let’s add the two we have:

>>> all_stats = stats + stats_de

The resulting Counter object contains all the elements from both original Counters:

>>> all_stats
Counter({'Joe': 5, 'Mary': 4, 'Ilse': 3, 'Luke': 2, 'Hans': 2, 'Dieter': 1})

You can also subtract Counter objects. Let’s remove the German names from all names. Then we’ll be left with just the English names:

>>> stats_eng = all_stats - stats_de
>>> stats_eng
Counter({'Joe': 5, 'Mary': 4, 'Luke': 2})

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Convert a Counter Object to a Dictionary

If you need a regular dictionary, you can use the dict function along with the items method on the Counter object:

>>> dict(stats_eng.items())
{'Joe': 5, 'Mary': 4, 'Luke': 2}

Here’s the video version of this article:


Spread the love

Leave a Reply