Updating a dictionary with integer keys
<p>I'm working on a short assignment where I have to read in a .txt file and create a dictionary in which the keys are the number of words in a sentence and the values are the number of sentences of a particular length.  I've read in the file and determined the length of each sentence already, but I'm having troubles creating the dictionary.  </p>

<p>I've already initialized the dictionary and am trying to update it (within a for loop that iterates over the sentences) using the following code:</p>

<pre><code>for snt in sentences:
    words = snt.split(' ')
    sDict[len(words)]+=1
</code></pre>

<p>It gives me a KeyError on the very first iteration.  I'm sure it has to do with my syntax but I'm not sure how else to update an existing entry in the dictionary.</p>

<p><code>defaultdicts</code> were invented for this purpose:</p>

<pre><code>from collections import defaultdict

sDict = defaultdict(int)
for snt in sentences:
    sDict[len(snt.split())] += 1
</code></pre>

<p>If you are restricted to the use of pure dictionaries in the context of your assignment, then you need to test for existence of the key before incrementing its value in order to prevent a <code>KeyError</code>:</p>

<pre><code>sDict = {}
for snt in sentences:
    num_words = len(snt.split())
    if num_words in sDict:
        sDict[num_words] += 1
    else:
        sDict[num_words] = 1
</code></pre>

python dictionary