-1

I'm trying to count how many times each letter appears in a piece of text.

def  count_letters(text):
    result = {}
    for letter in text:
        if letter not in result:
            result[letter]= 0
            result[letter] += 1
    return result
    
count_letters("aaad g a")

When I type this code however, it's only showing 1 as the values for each key. I was expecting 4 for a, 1 for d, etc

Robert
  • 7,394
  • 40
  • 45
  • 64

2 Answers2

2

Your indentation is off; you only increment the count the first time you see the letter.

def count_letters(text):
    result = {}
    for letter in text:
        if letter not in result:
            result[letter] = 0
        result[letter] += 1  # This must not happen only when you've not seen that letter yet, but each time
    return result
 
print(count_letters("aaad g a"))

This prints:

{'a': 4, 'd': 1, ' ': 2, 'g': 1}

Or maybe this version of the code is clearer?

def count_letters(text):
    result = {}
    for letter in text:
        if letter not in result:
            result[letter] = 1
        else:
            result[letter] += 1
    return result
 
print(count_letters("aaad g a"))

This sets the hash value to 1 the first time you see that letter, or increases the count every other time.

Robert
  • 7,394
  • 40
  • 45
  • 64
2

The result[letter] += 1 statement is indented to be under the if statement, so it will be only be executed the first time a letter is seen. Change the indentation level to be directly inside the for instead.

if letter not in result:
    result[letter] = 0
result[letter] += 1

A simpler method would be to use collections.defaultdict, which obviates the need to manually set the value to 0 on the first occurrence.

from collections import defaultdict
result = defaultdict(int)
for letter in text:
    result[letter] += 1
return result

Or even better, just use collections.Counter.

from collections import Counter
return Counter(text)
# or {**Counter(text)} to get a regular dict
Unmitigated
  • 76,500
  • 11
  • 62
  • 80