Counter
Counter is a quick way to return the frequency of characters in a string as a dictionary:
from collection import Counter
freq = Counter("apple") # Counter({'p': 2, 'a': 1, 'l': 1, 'e': 1})
print(freq["p"]) # 2
To add more stuff to the counter, we can use update()
. This will keep the previous dictionary and update new counter
freq = Counter("apple") # Counter({'p': 2, 'a': 1, 'l': 1, 'e': 1})
freq.update("pepper")
print(freq["p"]) # 5
Use cases: Anagram check