How do you make a Counter in Python?

To count items in list or create counter in Python we can:

**(1) Counting items in list **

The code below shows how to count numbers in Python stored in list:

from collections import Counter
Counter([4,1,4,3,4,5, 1])

result:

Counter({4: 3, 1: 2, 3: 1, 5: 1})

**(2) counting letters in Python **

To count letters in a given text we can use again Counter from collections

from collections import Counter
Counter("hot dog")

result:

Counter({'h': 1, 'o': 2, 't': 1, ' ': 1, 'd': 1, 'g': 1})

(3) Count and sort with Pandas

Alternatively we can use pandas to convert any sequence to Pandas Series and get the counts sorted:

import pandas as pd
numbers = [4,1,4,3,4,5, 1]
counts = [el if el < 10 else el % 10 for el in numbers]
pd.Series(counts).value_counts().to_dict()

result:

{4: 3, 1: 2, 3: 1, 5: 1}

(4) Collections counter sorted

from collections import Counter
x = Counter({'apple': 2, 'orange': 1, 'pear': 4})
x.most_common()

result:

[('pear', 4), ('apple', 2), ('orange', 1)]

(5) Python Counter Examples

How to create and use counter in Python with iter

from collections import Counter

# empty Counter
counter = Counter()
print(counter)

# Counter with initial values
counter = Counter(['h', 'e', 'l', 'l', 'o'])
print(counter)

counter = Counter(a=4, b=5, c=2)
print(counter)

word_count_dict = {'apple': 2, 'orange': 1, 'pear': 4}
counter = Counter(word_count_dict)
print(counter) 


result:

Counter()
Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})
Counter({'b': 5, 'a': 4, 'c': 2})
Counter({'pear': 4, 'apple': 2, 'orange': 1})

Resources