You can solve this easily by using collections.Counter
. Counter is a subtype of the standard dict that is made to count things. It will automatically make sure that indexes are created when you try to increment something that hasn’t been in the dictionary before, so you don’t need to check it yourself.
You can also pass any iterable to the constructor to make it automatically count the occurrences of the items in that iterable. Since a string is an iterable of characters, you can just pass your string to it, to count all characters:
>>> import collections
>>> s = 'ddxxx'
>>> result = collections.Counter(s)
>>> result
Counter({'x': 3, 'd': 2})
>>> result['x']
3
>>> result['d']
2
Of course, doing it the manual way is fine too, and your code almost works fine for that. Since you get a KeyError
, you are trying to access a key in the dictionary that does not exist. This happens when you happen to come accross a new character that you haven’t counted before. You already tried to handle that with your if i in s
check but you are checking the containment in the wrong thing. s
is your string, and since you are iterating the character i
of the string, i in s
will always be true. What you want to check instead is whether i
already exists as a key in the dictionary result
. Because if it doesn’t you add it as a new key with a count of 1
:
if i in result:
result[i] += 1
else:
result[i] = 1