Reputation: 1886
I am trying to count the numbers of each character in a string
My code here:
def CharCount(string):
mydict = {}
for char in string:
mydict[char] = mydict.get(char) + 1
return '\n'.join(['%s,%s' % (c, n) for c, n in mydict.items()])
if __name__ == '__main__':
print CharCount("abcda")
On running above code I am getting below error:
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
Upvotes: 0
Views: 9608
Reputation: 1124
When you do aceess char
for the first time, dict.get(char)
returns None
, not 0
. This should solve:
mydict[char] = (mydict.get(char) if char in mydict else 0) + 1
Upvotes: 1
Reputation: 336108
dict.get(key)
returns None
by default if key
isn't in the dictionary. Provide a useful default value instead:
for char in string:
mydict[char] = mydict.get(char, 0) + 1
However, there exists a better method: collections.defaultdict
:
from collections import defaultdict
mydict = defaultdict(int)
for char in string:
mydict[char] += 1
from collections import Counter
mydict = Counter(string)
Upvotes: 5