+ 1

Letter counter

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 = {} #your code goes here for letter in text : key =str (letter ) value = text .count(letter ) print ({key : value }) Plz help🤪

27th Jun 2021, 7:56 AM
Tharushi Senarath
Tharushi Senarath - avatar
7 Answers
+ 10
Try this text = input() dict = {} #your code goes here for char in text: counts = text.count(char) dict[char] = counts print(dict)
14th Jul 2021, 8:51 PM
Seyed Amin Naghavi
Seyed Amin Naghavi - avatar
+ 7
You've almost got it, but your code only prints the last key: value pair created. You need to create your dictionary, pair by pair, then print it. The easiest way is using a comprehension like this (using set() eliminates duplicates): letters = {letter: text.count(letter) for letter in set(text)} print(letters) Here's an example https://code.sololearn.com/c5SZz6Ecsnqz
27th Jun 2021, 8:19 AM
David Ashton
David Ashton - avatar
+ 4
# the most efficient (and shortest) way would be to use Counter object from collections module: from collections import Counter print(dict(Counter(text)))
27th Jun 2021, 11:23 AM
visph - avatar
+ 2
Thank u all😇
27th Jun 2021, 8:23 AM
Tharushi Senarath
Tharushi Senarath - avatar
+ 1
text = input() dict = {} count = 0 for i in text: count = text.count(i) dict[i] = count print(dict)
30th Oct 2022, 5:43 PM
Rafael Mina Piergiorge
Rafael Mina Piergiorge - avatar
Can you tell what output u want give more details about Question u have posted code only
27th Jun 2021, 7:58 AM
ASR - avatar
David Ashton why does it print only the last pair?
26th Jun 2022, 10:48 PM
Ackumey Joseph