#python

Today, I learned about the Counter class in Python.

The idea was that I had a list of dates (after parsing a log file) and I needed to count the number of occurrences of each date in that list.

The list looked something like this:

 1data = ['2023-02-17',
 2 '2023-02-17',
 3 '2023-02-17',
 4 '2023-02-17',
 5 '2023-02-17',
 6 '2023-02-17',
 7 '2023-02-17',
 8 '2023-02-18',
 9 '2023-02-18',
10 '2023-02-18',
11 '2023-02-18',
12 '2023-02-18',
13 '2023-02-18',
14 '2023-02-18',
15 '2023-02-18',
16 '2023-02-20',
17 '2023-02-20',
18 '2023-02-20',
19 '2023-02-20',
20 '2023-02-20',
21 '2023-02-20',
22 '2023-02-20',
23 '2023-02-20',
24 '2023-02-20',
25 '2023-02-20',
26 '2023-02-20',
27 '2023-02-20',
28 '2023-02-20',
29 '2023-02-20',
30 '2023-02-20',
31 '2023-02-22',
32 '2023-02-22',
33 '2023-02-22',
34 '2023-02-22',
35 '2023-02-22',
36 '2023-02-22',
37 '2023-02-22',
38 '2023-02-22',
39 '2023-02-22',
40 '2023-02-22',
41 '2023-02-22',
42 '2023-02-22',
43 '2023-02-22',
44 '2023-02-22',
45 '2023-02-22',
46 '2023-02-22',
47 '2023-02-22',
48 '2023-02-22',
49 '2023-02-22',
50 '2023-02-22',
51 '2023-02-23',
52 '2023-02-23',
53 '2023-02-23',
54 '2023-02-23',
55 '2023-02-23',
56 '2023-02-23',
57 '2023-02-23',
58 '2023-02-23',
59 '2023-02-23',
60 '2023-02-23',
61 '2023-02-23',
62 '2023-02-23',
63 '2023-02-23',
64 '2023-02-27',
65 '2023-02-27',
66 '2023-02-27',
67 '2023-02-27',
68 '2023-02-27',
69 '2023-03-02',
70 '2023-03-02',
71 '2023-03-02',
72 '2023-03-02',
73 '2023-03-02',
74 '2023-03-03',
75 '2023-03-03',
76 '2023-03-03',
77 '2023-03-03',
78 '2023-03-03',
79 '2023-03-03',
80 '2023-03-03',
81 '2023-03-08',
82 '2023-03-08',
83 '2023-03-08',
84 '2023-03-08',
85 '2023-03-08',
86 '2023-03-08',
87 '2023-03-16',
88 '2023-03-16',
89 '2023-03-16',
90 '2023-03-16']

Using the Counter class, this becomes a very trivial task:

 1from collections import Counter
 2
 3counts = Counter(data)
 4
 5for i in counts:
 6    print(i, counts[i])
 7
 8## Output
 9# 2023-02-17 7
10# 2023-02-18 8
11# 2023-02-20 15
12# 2023-02-22 20
13# 2023-02-23 13
14# 2023-02-27 5
15# 2023-03-02 5
16# 2023-03-03 7
17# 2023-03-08 6
18# 2023-03-16 4