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>When you initialize the dictionary, it starts out empty. The next thing you do is look up a key so that you can update its value, but that key doesn't exist yet, because the dictionary is empty. The smallest change to your code is probably to use the <code>get</code> dictionary method. Instead of this:</p>

<pre><code>sDict[len(words)]+=1
</code></pre>

<p>Use this:</p>

<pre><code>sDict[len(words)] = sDict.get(len(words), 0) + 1
</code></pre>

<p>The <code>get</code> method looks up a key, but if the key doesn't exist, you are given a default value. The default default value is <code>None</code>, and you can specify a different default value, which is the second argument, <code>0</code> in this case.</p>

<p>The better solution is probably <code>collections.Counter</code>, which handles the common use case of counting occurrences:</p>

<pre><code>import collections
s = map(str.split, sentences)
sDict = collections.Counter(map(len, s))
</code></pre>

python dictionary