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
7
  • 2
    Use collections.Counter Commented Jul 18, 2019 at 20:06
  • I would like to fix the code above that will work. Commented Jul 18, 2019 at 20:08
  • 1
    OK, no problem, please just edit the question to reflect that. Commented Jul 18, 2019 at 20:10
  • Thanks I edited. Commented Jul 18, 2019 at 20:12
  • It's clearer if you explicitly say, like, "I'm aware of collections.Counter but want to make this myself". Also if you're asking about that specific error, you need to make a minimal reproducible example. Commented Jul 18, 2019 at 20:14

1 Answer 1

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}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.