How to get the character frequency of characters in a string using python? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to get the character frequency of characters in a string using python?

Sample : SOORAJ Output : {'S':1, 'O':2, 'R':1, 'A':1, 'J':1} This should be the output required. Using dictionaries, keys, loops, condition statement and function. Below is the code I got but dont know why keys is not defined before the loops. Can anyone please explain this to me. def ch_frq (str1): dict = {} for n in str1: keys=dict.keys() if n in keys: dict[n] +=1 else: dict[n]=1 return dict

15th Mar 2018, 10:12 AM
Fire-Fly
Fire-Fly - avatar
4 Answers
+ 3
The line “keys=dict.keys()” isn’t necessary. Try the following: def count(st): d = dict() for c in st: if c in d.keys(): d[c] += 1 else: d[c] = 1 return d mystr = "test" dd = count(mystr) print(dd)
15th Mar 2018, 10:55 AM
Pedro Demingos
Pedro Demingos - avatar
+ 1
Pedro Demingos Thank you sir for the answer
15th Mar 2018, 11:29 AM
Fire-Fly
Fire-Fly - avatar
+ 1
Generally the same as Pedro suggested, but shorter, and, may be a bit faster: def func(a): mydict = {} for x in a: mydict.setdefault(x,0) mydict[x] += 1 return mydict s = "sololearn" print(func(s))
15th Mar 2018, 2:19 PM
strawdog
strawdog - avatar
0
# Aqui sin funciones. s="sololearn" dict = {} for x in s: dict.setdefault(x,0) dict[x] += 1 print(dict)
15th Apr 2018, 10:51 PM
Luis Gonzalez
Luis Gonzalez - avatar