+ 2

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
8 Respuestas
+ 11
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
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
+ 1
def letter_count(text, letter): #your code goes here return text.count(letter) text = input() letter = input() print(letter_count(text, letter))
26th Feb 2023, 8:03 PM
Dan MARINESCU
0
Can you tell what output u want give more details about Question u have posted code only
27th Jun 2021, 7:58 AM
A S Raghuvanshi
A S Raghuvanshi - avatar
0
David Ashton why does it print only the last pair?
26th Jun 2022, 10:48 PM
Ackumey Joseph