6

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
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
Tomonaga
  • 167
  • 1
  • 5
  • 5
    Possible duplicate of [Word frequency with dictionary comprehension](https://stackoverflow.com/questions/40611865/word-frequency-with-dictionary-comprehension) – nofinator Jun 12 '19 at 13:32

2 Answers2

12

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})
gold_cy
  • 13,648
  • 3
  • 23
  • 45
  • 4
    while using count, it's better to use `for k in set(word)` , will reduce the iteration – sahasrara62 Jun 12 '19 at 13:34
  • if size of list is much(say 10^5 or more) for above method it will check for each character, count it frequency and overwrite the frequency again and again, in later first it will find the unique element and then count frequency. so it will save time, provided Memoization is there or not (don't know if it implemented in `count()` method or not), for example run the code for `word='aabcd'*100000` an for both case see time diference – sahasrara62 Jun 12 '19 at 13:41
  • 3
    Using a `Counter` being the proper solution (that's very exactly what this class is for), the debate on whether the OP should make the list a set is rather useless... – bruno desthuilliers Jun 12 '19 at 13:51
2

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}
Gábor Fekete
  • 1,343
  • 8
  • 16