[SOLVED] Letter Counter Intermediate Python | Sololearn: Learn to code for FREE!


[SOLVED] Letter Counter Intermediate Python

I'm stuck where the dictionary will only count one value for each letter, I would appreciate being pointed in the right direction on where to go from here.. text = input() dict = {} for x in text: dict[x] = x.count(x) if x in dict: dict[x] += 1 print(dict) Edit: solved by moving my if statement to the start of the for loop πŸ‘€

6/7/2021 11:21:15 AM

Bianca S

15 Answers

New Answer


see this code, I am checking that If keys or letters are avalible then just update the value by 1 , else make a key of name that letter and make it's values 1 https://code.sololearn.com/c4B7Zb7voT80/?ref=app


Here is what i did ,it works(it would help) text = input() dict = {} #your code goes here for i in text: if i not in dict: dict[i]=1 else: dict[i]+=1 print(dict)


Bianca S You could also use dictionary comprehension here: a = input() print({x:a.count(x) for x in set(a)}) # Hope this helps


Hasnae Bouhmady your solution is the best !


""" you could also use the built-in Counter class from 'collections' module, wich return a dict-like, wich can be easily converted to a real dict: """ from collections import Counter text = input() print(dict(Counter(text))) # https://pymotw.com/2/collections/counter.html


Try this code I tried it using dictionary comprehension text = input() dic = {I: text.count(i) for i in text } print(dic)



What do dict={} do?


@saad Khan dict={} is an empty dictionary ,you need to declare it first and then you can fill in it whith keys and values


Calvin Thomas technically your code is doing what is wanted but they want in order according to order of input letters so that's why it doesn't really works.


Here is what I did text = input() dict = {} #your code goes here for i in text: w = 1 if i in dict: w = text.count(i) dict [i] = w else: dict[i] = w print (dict)


# These three solutions for help: #solving number 1: text = input() #your code goes here from collections import Counter c = Counter(text) print(dict(c)) #solving number 2: word = input('Enter word: ') d = dict() for i in word: d[i] = word.count(i) print(d) #solving number 3: word = input('Enter word: ') print({letter: word.count(letter) for letter in word})


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


If you want to use count you should use a function to return the dict this is for modifying code


for letters in text: if letters in dict.keys(): dict[letters] += 1 else: dict[letters] = 1 print(dict)