I have a list of strings, and I want to create a dictionary, where each word from the list will be in accordance with the number of its occurrences in the string.

That is, here is the code:

words = dict() for str in lst: words[str] += 1 

When I try to run the code, on the third line I get an error with the inscription:

 KeyError: 'in' 

What is the problem?

    1 answer 1

    words[str] += 1 equivalent to words[str] = words[str] + 1 , therefore, since words initially empty, words['in'] will call KeyError . To correct, you can use words = collections.defaultdict(int) , which initializes zero (the result of int() ) on the first call. Or better

     import collections words = collections.Counter(lst)