2

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
Avi
  • 2,247
  • 4
  • 30
  • 52

1 Answers1

2

There are two ways to do this:

In [94]: s = 'aackcdldccc'

In [95]: collections.Counter(s)
Out[95]: Counter({'a': 2, 'c': 5, 'k': 1, 'd': 2, 'l': 1})

In [96]: d = {}

In [97]: for char in s:
    ...:     d.setdefault(char, 0)
    ...:     d[char] += 1
    ...: 

In [98]: d
Out[98]: {'a': 2, 'c': 5, 'k': 1, 'd': 2, 'l': 1}
wjandrea
  • 28,235
  • 9
  • 60
  • 81
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241