Haresh Shyara
Haresh Shyara

Reputation: 1886

TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

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

Answers (2)

Lapshin Dmitry
Lapshin Dmitry

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

Tim Pietzcker
Tim Pietzcker

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

or collections.Counter:

from collections import Counter
mydict = Counter(string)

Upvotes: 5

Related Questions