Note

Python - Counter Dict - Simplify counting with collections


Overview of the Python Counter() dictionary. Make counting objects significantly easier!

Counter(iterable) is a subclass of Python dict built-in.

The Counter class is a variation of dictionary that makes counting of elements in iterables way easier.

Counter is designed for counting hashable items in an iterable. It provides an easy way to count elements in lists, strings, and other iterables, allowing you to access counts by calling the keys.

Counter has method most_common(n=None). It lists the n most common elements and their counts, (from high to low) in tuples. If you don't provide n, it lists all elements counts.

And Counter also has method elements(). It creates an iterator with elements repeating as many times as their count.

It also acts similar to defaultdict in some cases, when you will call a key that don't exist, Counter will return a 0.

To use Counter, you must import it from the collections module.

Take a look at examples below:


from collections import Counter

c1 = Counter([1, 5, 2, 2, 2, 5, 5, 5, 1])

print(c1)  # Counter({5: 4, 2: 3, 1: 2})
print(c1[5])  # 4
print(c1["i_dont_exist"])  # 0
print(c1.most_common(3))  # [(5, 4), (2, 3), (1, 2)]

c2 = Counter("devcuriosity")

print(c2)  # Counter({'i': 2, 'd': 1, 'e': 1, 'v': 1, 'c': 1, 'u': 1, 'r': 1, 'o': 1, 's': 1, 't': 1, 'y': 1})
print(c2["i"])  # 2
print(c2.most_common(3))  # [('i', 2), ('d', 1), ('e', 1)]

Output:

Counter({5: 4, 2: 3, 1: 2})
4
0
[(5, 4), (2, 3), (1, 2)]
Counter({'i': 2, 'd': 1, 'e': 1, 'v': 1, 'c': 1, 'u': 1, 'r': 1, 'o': 1, 's': 1, 't': 1, 'y': 1})
2
[('i', 2), ('d', 1), ('e', 1)]

Using elements() to Access Items by Frequency

from collections import Counter

c3 = Counter(["C", "B", "C", "B", "A", "C"])

print(c3)  # Counter({'C': 3, 'B': 2, 'A': 1})
print(c3.most_common(1))  # [('C', 3)]

for element in c3.elements():
    print(element)

Output:

Counter({'C': 3, 'B': 2, 'A': 1})
[('C', 3)]
C
C
C
B
B
A

Updating a Counter Using update()

It is worth mentioning that update() works in a different way in a Counter. Instead of replacing values, it increments the count for each element in the argument.

from collections import Counter

c4 = Counter(["A", "B"])

print(c4)  # Counter({'A': 1, 'B': 1})

c4.update(("A", "A", "B"))

print(c4)  # Counter({'A': 3, 'B': 2})

Output:

Counter({'A': 1, 'B': 1})
Counter({'A': 3, 'B': 2})

Key Points to Remember about Counter Dict

  • Efficient Counting: Counter offers a fast and easy way to count items in an iterable.

  • Automatic Handling of Missing Keys: Accessing a missing key returns 0 instead of raising a KeyError.

  • Useful Methods:

    • most_common(n=None): Quickly retrieve the most common items and their counts.

    • elements(): Access items by their frequency, creating a sequence with repeated items.

    • update(): Adds to the count of existing elements rather than replacing values.

I hope you found this helpful! If you have any feedback, questions or requests, please reach out to me through Contact page!

Thank You Image


You might also be interested in: