I am new to python but know basic commands. I am trying to create a for loop that, when defining a list of sentences, adds a key for the length of each sentence. The value of each key will be the frequency of this sentence length in the list, so the format will look something like this:
dictionary = {length1:frequency, length2:frequency, etc.}
I can’t find any previously asked questions that specifically concern this - creating keys using the main functions, and then changing the key value by the frequency of this result. Here is the code I have:
dictionary = {}
for i in sentences:
dictionary[len(i.split())] += 1
When I try to run the code, I get this message:
Traceback (most recent call last):
File "<pyshell#11>", line 2, in <module>
dictionary[len(i.split())] += 1
KeyError: 27
Any help correcting my code and explaining where I went wrong would be greatly appreciated!