0
Letter Counter(FAQ)
This is working code: text = input() dict = {} for i in text: if i in dict: dict[i] += 1 else: dict[i] = 1 print(dict) Please explain to me how text value come into dictionary? I can`t understand how it work.
5 Respostas
+ 2
Each letter from input text is extract by for loop and
by if part, tested if it's in dictionary, if yes then its value at that letter as key is incremented.
otherwise with that letter as key is added a value 1 by else part
ex: input 'letter'
i='l' , is in dict , false so dict['l']=1
i='e' , is in dict , false so dict['e']=1
i='t' , is in dict , false so dict['t']=1
i='t' , is in dict , true so dict['t'] +=1, dict['t']=2
i='e' , is in dict , true so dict['e'] +=1, dict['e']=2
i='r' , is in dict , false so dict['r']=1
Hope it helps...
+ 2
? Mark?
Is it mean not clear yet?
In for loop:
That is, with each iteration of the "for" loop,
By else part : each new letter from the input text is entered into the dictionary,
or
By if part : the value of the letter that is already in the dictionary increased by 1.
Now hope it clear..
+ 1
With the for loop you've already got every single character(i) in the text. You need to write code like dict[i] = 1 to add it to this dictionary. This adds i as the key and 1 as the values of i to the dictionary.
+ 1
That is, with each iteration of the "for" loop, each new letter from the input text is entered into the dictionary, or is the value of the letter that is already in the dictionary increased by 1?
Thanks for everybody!!!
+ 1
It was just thinking out loud with a question mark. I got it. Thanks again!