Item frequency count in Python Item frequency count in Python python python

Item frequency count in Python


The Counter class in the collections module is purpose built to solve this type of problem:

from collections import Counterwords = "apple banana apple strawberry banana lemon"Counter(words.split())# Counter({'apple': 2, 'banana': 2, 'strawberry': 1, 'lemon': 1})


defaultdict to the rescue!

from collections import defaultdictwords = "apple banana apple strawberry banana lemon"d = defaultdict(int)for word in words.split():    d[word] += 1

This runs in O(n).


freqs = {}for word in words:    freqs[word] = freqs.get(word, 0) + 1 # fetch and increment OR initialize

I think this results to the same as Triptych's solution, but without importing collections. Also a bit like Selinap's solution, but more readable imho. Almost identical to Thomas Weigel's solution, but without using Exceptions.

This could be slower than using defaultdict() from the collections library however. Since the value is fetched, incremented and then assigned again. Instead of just incremented. However using += might do just the same internally.