Tomonaga
Tomonaga

Reputation: 167

Rewrite to dictionary comprehensions

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

Upvotes: 6

Views: 405

Answers (2)

gold_cy
gold_cy

Reputation: 14216

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})

Upvotes: 12

Gábor Fekete
Gábor Fekete

Reputation: 1358

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}

Upvotes: 2

Related Questions