August 2018
Intermediate to advanced
366 pages
10h 14m
English
Relying on Counter is actually not the only way to track frequencies; we already know that Counter is a special kind of dictionary, so reproducing the Counter behavior should be quite straightforward.
Probably every one of us came up with a dictionary in this form:
counts = dict(hello=0, world=0, nice=0, day=0)
Whenever we face a new occurrence of hello, world, nice, or day, we increment the associated value in the dictionary and call it a day:
for word in 'hello world this is a very nice day'.split():
if word in counts:
counts[word] += 1
By relying on dict.get, we can also easily adapt it to count any word, not just those we could foresee:
for word in 'hello world this is a very nice day'.split(): counts[word] = counts.get(word, ...