September 2026
1051 pages
35h 4m
English
It often happens that you’re interested in the frequency distribution of the elements of an iterable object—for example, how often individual letters occur in a string.[ 62 ] This problem can be elegantly solved with a dictionary:
>>> t = "This is the text">>> d = {}>>> for c in t:... if c in d:... d[c] += 1... else:... d[c] = 1...>>> d{'T': 1, 'h': 2, 'i': 2, 's': 2, ' ': 3, 't': 3, 'e': 2, 'x': 1}
The Counter data type of the collections module is a dictionary that returns the value 0 when a key is accessed that does not exist. This data type can be used to simplify the code shown previously:
>>> t = "This is the text">>> d = collections.Counter()>>> for c in t:... d[c] += 1...>>> dCounter({' ': 3, 't': 3, 'h': ...
Read now
Unlock full access