Can someone explain what do i do? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can someone explain what do i do?

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} just explain not slove it

18th Apr 2021, 8:44 AM
karimireza77
karimireza77 - avatar
4 Answers
+ 6
Get the input Create an empty dict. Loop over each letter in the input string. In the loop check if the letter is in the dict as a key. If no, add a new element to the dict, using the letter as a key and set it's value to 1. If yes, then increment the value held for that key by 1. After the loop output the dict.
18th Apr 2021, 9:08 AM
ChaoticDawg
ChaoticDawg - avatar
+ 4
Reza Karimi Show your attempts. Hint :- use dictionary to count
18th Apr 2021, 8:48 AM
A͢J
A͢J - avatar
+ 2
It's not taught in the course, and not the point of this particular lesson, but you could also use Counter from the collections module. from collections import Counter print(dict(Counter(input()))) Counter(iterable) will return a Counter object that is like a dictionary that will have the element as the key and the count of matching elements as the value. You would then convert that into a dict() and output it. Which can all be done in 1 line like shown.
18th Apr 2021, 9:18 PM
ChaoticDawg
ChaoticDawg - avatar
0
classic method: 1- declare an empty dictionary 2- loop through the word using for loop: for letter in word 3- if letter in dictionary than dictionary[letter] += 1 else dictionary.update({letter:1}) 4- print dictionary
18th Apr 2021, 8:34 PM
iTech
iTech - avatar