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

-4

[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

13 Answers

New Answer

+8

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

+11

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)

+7

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

+3

Hasnae Bouhmady your solution is the best !

+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

What do dict={} do?

+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

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.

0

# 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})

0

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

-2

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