brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: collections.Counter.most_common for counting things

Scripting
~/tips/tip-python-counter-most-common

from collections import Counter

Counts items in any list and returns the most frequent ones.

Whenever I count items with a dict and an if key in d check, I am doing work that collections.Counter already does.

Counter counts the elements of any iterable, and most_common(n) returns the top n with their counts:

from collections import Counter

ips = ["192.168.1.5", "192.168.1.7", "192.168.1.5"]
print(Counter(ips).most_common(1))
# [('192.168.1.5', 2)]

It fits log files, where you pull one field out of every line and count it:

lines = ["GET /a 200", "GET /b 404", "GET /a 200", "POST /a 500"]
print(Counter(l.split()[1] for l in lines).most_common(2))
# [('/a', 3), ('/b', 1)]

The docs show Counter('abracadabra').most_common(3) giving [('a', 5), ('b', 2), ('r', 2)] and say that elements with equal counts are ordered in the order first encountered. Leave out n to get every element, sorted. The method update() adds counts instead of replacing them, so you can feed a Counter several files in a row, and total(), added in Python 3.10, gives the sum of all counts.

Caveats: a Counter holds every distinct key in memory, so millions of unique values still cost memory. And the + and - operators keep only positive counts. Counter(a=3) - Counter(a=5) gives an empty Counter, not a: -2. Use subtract() when you want negative numbers to survive.

Further reading: collections.Counter

More Scripting tips import difflib $r = Invoke-RestMethod https://api.github.com/repos/PowerShell/PowerShell/releases/latest import json, os, tempfile import shutil from contextlib import chdir All Scripting tips (10) All topics

Link