counter most common python 3 code example

Example 1: python counter least common

from collections import Counter
data_list = [1,1,2,2,2,2,3,3,3,3,3,3,3,4,4,4,4,4,4,4]
least_common = Counter(data_list).most_common()[-1]
print(least_common)
# The number 1 appears 2 times
(1, 2)

Example 2: python counter

>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]

Example 3: python counting dictionary

counts = dict()
for i in items:
  counts[i] = counts.get(i, 0) + 1

Example 4: python counter least common

import collections
c = collections.Counter(a=1, b=2, c=3)
n = 2

print c.most_common()[:-n-1:-1]Output[('a', 1), ('b', 2)]