+ 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
4 Respuestas
+ 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)
+ 1
Pedro Demingos 
Thank you sir for the answer
+ 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))
0
# Aqui sin funciones.
s="sololearn"
dict = {}
for x in s:
        dict.setdefault(x,0)
        dict[x] += 1
print(dict)



