Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 311
Tomonaga Avatar asked Jun 12 '19 13:06

Tomonaga


2 Answers

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})
like image 77
gold_cy Avatar answered Sep 28 '22 07:09

gold_cy


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}
like image 35
Gábor Fekete Avatar answered Sep 28 '22 07:09

Gábor Fekete