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

-2

[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

11 Answers

New Answer

+7

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

+5

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

+2

""" 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

+2

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

+1

+1

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

+1

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)

+1

Hasnae Bouhmady your solution is the best !

0

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

0

What do dict={} do?

0

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.