I want to count occurrence of all letters in a word using dictionary. So far I've tried adding to dict in for loop.
I wonder is it possible to use dictionary comprehensions?
word = "aabcd"
occurrence = {}
for l in word.lower():
if l in occurrence:
occurrence[l] += 1
else:
occurrence[l] = 1
Sure it is possible.
Use a Counter
.
from collections import Counter
c = Counter(word)
print(c)
Counter({'a': 2, 'b': 1, 'c': 1, 'd': 1})
Another solution using defaultdict.
from collections import defaultdict
occurrence = defaultdict(int)
for c in word.lower():
occurrence[c] += 1
print(occurrence)
defaultdict(<class 'int'>, {'a': 2, 'b': 1, 'c': 1, 'd': 1})
Or another one without using any imports.
occurrence = {}
for c in word.lower():
occurrence[c] = occurrence.get(c,0) + 1
print(occurrence)
{'a': 2, 'b': 1, 'c': 1, 'd': 1}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With