Letter counter | Sololearn: Learn to code for FREE!


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🤪

6/27/2021 7:56:20 AM

Tharushi Senarath

6 Answers

New Answer


Try this text = input() dict = {} #your code goes here for char in text: counts = text.count(char) dict[char] = counts print(dict)


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


# the most efficient (and shortest) way would be to use Counter object from collections module: from collections import Counter print(dict(Counter(text)))


Thank u all😇


Can you tell what output u want give more details about Question u have posted code only


David Ashton why does it print only the last pair?