+ 1

Why it doesn't print all the dictionaries? ( SOLVED!!!)

x = input () D = {} for i in x: D = { i : x. count(i) } print(D) I need to print exg: input = " awesome " Output should {'a' :1, 'w':1, 'e':1, 's':1, 'o':1, 'm':1, 'e':2}

18th Jun 2021, 2:47 PM
SelvaKumar
3 Respostas
+ 4
Because you recreate dictionary <D> to contain only a letter (represented by variable <i> in for-loop) and count of the letter in the given input string. A dictionary can't have duplicate key, so you can't have 'e' : 1 and 'e' : 2 together in the dictionary.
18th Jun 2021, 2:55 PM
Ipang
+ 4
SelvaKumar , here is a base code you can use and fill in the required code for the 2 cases: str = input() res = {} for i in str: if i in res: # (fill in the code): if character already exists in dict: increment value by 1 else: # (fill in the code): if character not exists, creare a new member in dict with character as key and 1 as value print(res)
18th Jun 2021, 3:21 PM
Lothar
Lothar - avatar
+ 2
Your code shows only the last run. Last e is two times in the input. Correct line 4 to D[i] = x.count(i)
18th Jun 2021, 3:22 PM
Angela
Angela - avatar