We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
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:
data = ['2023-02-17',
'2023-02-17',
'2023-02-17',
'2023-02-17',
'2023-02-17',
'2023-02-17',
'2023-02-17',
'2023-02-18',
'2023-02-18',
'2023-02-18',
'2023-02-18',
'2023-02-18',
'2023-02-18',
'2023-02-18',
'2023-02-18',
'2023-02-20',
'2023-02-20',
'2023-02-20',
'2023-02-20',
'2023-02-20',
'2023-02-20',
'2023-02-20',
'2023-02-20',
'2023-02-20',
'2023-02-20',
'2023-02-20',
'2023-02-20',
'2023-02-20',
'2023-02-20',
'2023-02-20',
'2023-02-22',
'2023-02-22',
'2023-02-22',
'2023-02-22',
'2023-02-22',
'2023-02-22',
'2023-02-22',
'2023-02-22',
'2023-02-22',
'2023-02-22',
'2023-02-22',
'2023-02-22',
'2023-02-22',
'2023-02-22',
'2023-02-22',
'2023-02-22',
'2023-02-22',
'2023-02-22',
'2023-02-22',
'2023-02-22',
'2023-02-23',
'2023-02-23',
'2023-02-23',
'2023-02-23',
'2023-02-23',
'2023-02-23',
'2023-02-23',
'2023-02-23',
'2023-02-23',
'2023-02-23',
'2023-02-23',
'2023-02-23',
'2023-02-23',
'2023-02-27',
'2023-02-27',
'2023-02-27',
'2023-02-27',
'2023-02-27',
'2023-03-02',
'2023-03-02',
'2023-03-02',
'2023-03-02',
'2023-03-02',
'2023-03-03',
'2023-03-03',
'2023-03-03',
'2023-03-03',
'2023-03-03',
'2023-03-03',
'2023-03-03',
'2023-03-08',
'2023-03-08',
'2023-03-08',
'2023-03-08',
'2023-03-08',
'2023-03-08',
'2023-03-16',
'2023-03-16',
'2023-03-16',
'2023-03-16']
Using the Counter class, this becomes a very trivial task:
from collections import Counter
counts = Counter(data)
for i in counts:
print(i, counts[i])
## Output
# 2023-02-17 7
# 2023-02-18 8
# 2023-02-20 15
# 2023-02-22 20
# 2023-02-23 13
# 2023-02-27 5
# 2023-03-02 5
# 2023-03-03 7
# 2023-03-08 6
# 2023-03-16 4
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.