+ 2

[solved] What to do next??

Given a string as input, you need to output how many times each letter appears in the string. You decide to store the data in a dictionary, with the letters as the keys, and the corresponding counts as the values. Create a program to take a string as input and output a dictionary, which represents the letter count. Sample Input hello Sample Output {'h': 1, 'e': 1, 'l': 2, 'o': 1} My code: text = input() dict = {} #your code goes here for x in text: if x in dict.keys(): dict[x] += 1 else: dict[x] = 1 print(dict)

1st Aug 2021, 10:22 AM
Aashay
3 Answers
+ 2
You are taking wrong approach here. You need to go through the text and check whether each letter is in the dictionary. If it is increase its value by 1. If it's not create new key with value of 1. If you will still have problems I could post how I solved it here)))
1st Aug 2021, 10:33 AM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
+ 1
Hi Aashay! Yes, your solution is correct. Now, you have to move to the next step to make it as a small lines of code. For that, you can use in-built functions. I solved this project by using both update() and count() functions. Here it is that solution. text = input() dict = {} for i in text: dict.update({i : text.count(i)}) print(dict)
1st Aug 2021, 12:08 PM
Python Learner
Python Learner - avatar
+ 1
Python Learner Thanks!!
1st Aug 2021, 12:36 PM
Aashay