0

Need explanation please !?

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} Text = input () dict = {} for x in text : if x not in dict : print (dict) #output : {} {} {} {} {} {} {} {} Help !

23rd Oct 2021, 1:06 PM
ola Scar
ola Scar - avatar
6 Respuestas
+ 1
ola Scar Since there is no key:value in dictionary and we are checking 1st character not exist in dictionary so we will add first character in string with count 1. Next time if we check another character and if that character is exist then we will increase counter by 1 which is in else part
23rd Oct 2021, 6:19 PM
A͢J
A͢J - avatar
+ 2
ola Scar Do this if character not exist in dict. If exist then increment 1 if x not in dict: dict[x] = 1 else: dict[x] += 1
23rd Oct 2021, 1:25 PM
A͢J
A͢J - avatar
+ 1
Nicest, thks
23rd Oct 2021, 7:38 PM
ola Scar
ola Scar - avatar
+ 1
a=input() print({i:a.count(i) for i in a})
24th Oct 2021, 12:27 PM
Prabhas Koya
0
Thanks, explain me this line dict[x] = 1
23rd Oct 2021, 5:22 PM
ola Scar
ola Scar - avatar
0
You used the count () function inside the dictionary, it reduces the code. Interesting !!
24th Oct 2021, 9:59 PM
ola Scar
ola Scar - avatar