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.
dict[text[k]]- it does not depend on the variable you keep using for counting. You can instead dodict[text[k]] += 1in your upper check, anddict[text[k]] = 1in your lowerelse. However, you can do this by doingfrom collections import Counterandcnt = Counter(text); no need to go through the text step by step. Another thing - do not name your dictdict-dictis an internally defined function that creates a dictionary.ababba, it's fun!count = 1=)