1

I'm trying to count how many times each letter appears in the string and then display it in a list eg. The word "hello" would be: {h:1, e:1, l:2, o:2} This is my code.

    text = input()
    dict = {}
    
    for k in range(len(text)):
      if text[k] in dict:
         count +=1
         dict.update({text[k]:count})
      else:
         count=1
         dict.update({text[k]:count})        


    print(dict)

The code works on smaller words but not for words that are >10 Can someone please point out what is wrong or what I am missing.

8
  • Please provide example(s) that don't work. Commented Jun 27, 2022 at 19:50
  • 1
    You're resetting the count each time, but the count depends on the current value inside your dict[text[k]] - it does not depend on the variable you keep using for counting. You can instead do dict[text[k]] += 1 in your upper check, and dict[text[k]] = 1 in your lower else. However, you can do this by doing from collections import Counter and cnt = Counter(text); no need to go through the text step by step. Another thing - do not name your dict dict - dict is an internally defined function that creates a dictionary. Commented Jun 27, 2022 at 19:50
  • Examples that don't work are words like incomprehensibilities, Tergiversation Commented Jun 27, 2022 at 19:56
  • It's not about the length, it's about letter order. Try ababba, it's fun! Commented Jun 27, 2022 at 19:57
  • 1
    @MarkRansom, there it is, I can distinctly see count = 1 =) Commented Jun 27, 2022 at 20:01

2 Answers 2

2

You can use the following code to count letter frequencies:

d = {}
for letter in text:
    d[letter] = d.get(letter, 0) + 1
print(d)
Sign up to request clarification or add additional context in comments.

3 Comments

OP is definitely learning to code, so it's more useful to point out their mistake, instead of using magic class to do everything for them =)
Can you please explain what the code does new to python.
@DanielHao: "When learning a new language…" — I'm pretty sure he learns his first language.
0

I've changed your code around a bit that seems to work:

trans = {}
def letterCounter(num):
    for ch in num.lower():
        if ch in trans.keys():
            trans[ch] += 1;
        else:
            trans[ch] = 1;
            
    print('Counts letters shown in the input:')
    for x in sorted(trans):
        print(f"Letter \"{x}\": {trans[x]}")

try:
    usr = input('Please insert your input & press ENTER to count its letters: ')
    letterCounter(usr)
except ValueError:
    print('Input must contain a word or sentence')

I know this is a little bit different than what you asked for, but this seems to work very well, and I used www.cologic.dev to do it. It uses code completion to help you learn and code more efficiently.

1 Comment

@Marcus np. use LAUNCH50 when signing up, and let me know if you need more help with code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.