I have a string l1
that for example contains the following content: aackcdldccc
. I would like to count the number of times that each character occurs using dictionary. The required final result should be a dictionary like this:
a:2
c:5
k:1
d:2
l:1
How can I fix my code so it will work? I use the following code and get error message:
l1= ('aackcdldccc')
print (l1)
d={}
print (len(l1))
for i in (range (len(l1))):
print (i)
print (l1[i])
print (list(d.keys()))
if l1[i] in list(d.keys()):
print ('Y')
print (l1[i])
print (list(d.keys())[l1[i]])
d1 = {l1[i]:list(d.values())[l1[i]+1]}
#print (d1)
#d.update (d1)
else:
print ('N')
d1={l1[i]:1}
d.update (d1)
Here is the error I get: aackcdldccc
11
0
a
[]
N
1
a
['a']
Y
a
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-185-edf313da1f8d> in <module>()
10 print ('Y')
11 print (l1[i])
---> 12 print (list(d.keys())[l1[i]])
13 #d1 = {l1[i]:list(d.values())[l1[i]+1]}
14 #print (d1)
TypeError: list indices must be integers or slices, not str