Counter Objects in Python Quick Overview

The Counter class is a convenient way to provide quick tallies for hashable objects. A Counter is a dict subclass meaning that it’s instances inherit many of the methods and properties of the dict class. The elements in Counter objects are stored as dictionary keys, and their respective counts as values. The Counter class in python is similar to bags or multisets in other programming languages. Here’s how the Counter signature looks:

class collections.Counter([iterable-or-mapping])

Below is an example of a Counter in action:

>>> from collections import Counter
>>> letters = ['a', 'a', 'b', 'b', 'c', 'd', 'e', 'e', 'f', 'f','f', 'g', 'h', 'h', 'i', 'j']
>>> cnt = Counter()
>>> for char in letters:
        cnt[char] += 1
>>> cnt
Counter({'f': 3, 'a': 2, 'b': 2, 'e': 2, 'h': 2, 'c': 1, 'd': 1, 'g': 1, 'i': 1, 'j': 1})

Creating Counter Objects in Python

Below are some ways in which you can construct a Counter in python:

>>> from collections import Counter
>>> c = Counter()
>>> name = Counter('Dougie D')
>>> name
Counter({'D': 2, 'o': 1, 'u': 1, 'g': 1, 'i': 1, 'e': 1, ' ': 1})
>>> colors = Counter({'blue': 3, 'black': 10, 'purple': 5})
>>> colors
Counter({'black': 10, 'purple': 5, 'blue': 3})
>>> pets
Counter({'cats': 10, 'dogs': 3})
>>> pets = Counter(dogs = 3, cats = 10)
============================================================================ Want to learn how to use Python's most popular IDE Pycharm? In the free pdf guide "Getting the Hang of PyCharm" you'll learn all of the amazing features in PyCharm along with how to get started with data science. Subscribe to the Purcell Consult newsletter and get started A.S.A.P.