List element frequencies

Lists (data structures)

How to count the frequency of the elements in a list?

import collections

# create a list

x = ['A', 'A', 'B' ,'C', 'C', 'C', 'C', 'D', 'D', 'E']

# get frequencies

c=collections.Counter(x)

Counter({'C': 4, 'A': 2, 'D': 2, 'B': 1, 'E': 1})

c.keys()

['A', 'C', 'B', 'E', 'D']

c.values()

[2, 4, 1, 1, 2]

# print frequencies, sorted by list elements

for item in sorted(c.keys()):

    print( item + ': ' + str(c[item]) )

A: 2

B: 1

C: 4

D: 2

E: 1

# print top 3 most frequent elements

c.most_common(3)

[('C', 4), ('A', 2), ('D', 2)]

for k,n in c.most_common(3):

     print(k + ': ' + str(n))

C: 4

A: 2

D: 2

# convert c into a dictionary

d = dict(c)

{'A': 2, 'C': 4, 'B': 1, 'E': 1, 'D': 2}

# convert c into a list

n = c.most_common()

[('C', 4), ('A', 2), ('D', 2), ('B', 1), ('E', 1)]