Ben Chuanlong Du's Blog

It is never too late to learn.

Count Frequencies of Elements Using collections.Counter in Python

Tips

collections.Counter is similar to a dict object. You can iterate through it similarly to how you iterate through a dict.

In [25]:
from collections import Counter

x = [1, 2, 3, 4, 5, 5, 4, 3, 3]
cntr = Counter(x)
cntr
Out[25]:
Counter({1: 1, 2: 1, 3: 3, 4: 2, 5: 2})
In [27]:
cntr.items()
Out[27]:
dict_items([(1, 1), (2, 1), (3, 3), (4, 2), (5, 2)])
In [28]:
cntr.values()
Out[28]:
dict_values([1, 1, 3, 2, 2])
In [29]:
cntr.values()
Out[29]:
dict_values([1, 1, 3, 2, 2])
In [ ]:
 

Comments