0

why it is not working for Letter Counter in intermediate python

text = input() dict = {} for x in text: dict[x]+=1 print(dict) I have done this without checking dict using if

25th Aug 2021, 3:25 AM
Sourav O
Sourav O - avatar
3 Answers
+ 3
The code outputs error if x is not a key of dict.
25th Aug 2021, 3:52 AM
ä½ ēŸ„é“č¦å‰‡ļ¼Œęˆ‘也ę˜Æ
ä½ ēŸ„é“č¦å‰‡ļ¼Œęˆ‘也ę˜Æ - avatar
+ 2
JUMP_LINK__&&__Python__&&__JUMP_LINK Building up based on CarrieForle's answer, here are three possibilities: text = input() dict = {} #1 for x in text: if x in dict: dict[x] += 1 else: dict[x] = 1 print(dict) #2 for x in text: dict = dict.get(x, 0) + 1 print(dict) Or just #3 print({x: text.count(x) for x in text}) # I hope that this answer helps you with your question. If I have made a mistake in any part of my answer, just let me know. Happy coding!
25th Aug 2021, 4:24 AM
Calvin Thomas
Calvin Thomas - avatar
+ 1
JUMP_LINK__&&__Python__&&__JUMP_LINK Your code will give error because there is no key in dictionary so 1st you need to check if key exist in dictionary then increment counter otherwise assign 1 to dictionary. text = input() dict = {} for x in text: if x in dict: dict[x]+=1 else: dict[x] = 1 print(dict) https://code.sololearn.com/cebXGf11Gq58/?ref=app
25th Aug 2021, 5:33 AM
AĶ¢J
AĶ¢J - avatar