How to build a dictionary of string lengths using a for loop?
<p>I am pretty new to python, but I know the basic commands. I am trying to create a for loop which, when given a list of sentences, adds a key for the length of each sentence. The value of each key would be the frequency of that sentence length in the list, so that the format would look something like this:</p>

<pre><code>dictionary = {length1:frequency, length2:frequency, etc.}
</code></pre>

<p>I can't seem to find any previously answered questions that deal with this specifically - creating keys using basic functions, then changing the key's value by the frequency of that result. Here is the code I have:</p>

<pre><code>dictionary = {}
for i in sentences: 
    dictionary[len(i.split())] += 1
</code></pre>

<p>When I try to run the code, I get this message:</p>

<pre><code>Traceback (most recent call last):
  File "&lt;pyshell#11&gt;", line 2, in &lt;module&gt;
    dictionary[len(i.split())] += 1
KeyError: 27
</code></pre>

<p>Any help fixing my code and an explanation of where I went wrong would be so appreciated!</p>

<p>I think this will solve your problem, in Python 3:</p>

<pre><code>sentences ='Hi my name is xyz'
words = sentences.split()
dictionary ={}
for i in words: 
    if len(i) in dictionary:
        dictionary[len(i)]+=1
    else:
        dictionary[len(i)] = 1
print(dictionary)
</code></pre>

<p>Output:</p>

<pre><code>{2: 3, 3: 1, 4: 1}
</code></pre>

<p>In dictionary, first you have to assign some value to key then only you can use that value for further calculations Or else there is alternative use <code>defaultdict</code> to assign default value to each key.</p>

<p>Hope this helps.</p>

python string list dictionary sentence