Extract the year and the month from a line in a file and use a map to print every time its found to add 1 to the value
<pre><code>def Stats():
    file = open('mbox.txt')
    d = dict()
    for line in file:
        if line.startswith('From'):
            words = line.split()
            for words in file:
                key = words[3] + " " + words[6]
                if key:
                    d[key] +=1
    return d
</code></pre>

<p>The line reads</p>

<pre><code>From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008
</code></pre>

<p>I want to pull "Jan 2008" as the key   </p>

<p>My error message: </p>

<pre><code>Traceback (most recent call last):
  File "C:\Users\Robert\Documents\PYTHON WORKSPACE\Program 1.py", line 78, in &lt;module&gt;
  File "C:\Users\Robert\Documents\PYTHON WORKSPACE\Program 1.py", line 76, in &lt;module&gt;
  File "C:\Users\Robert\Documents\PYTHON WORKSPACE\Program 1.py", line 63, in &lt;module&gt;
builtins.KeyError: 'u -'
</code></pre>

<p>You need something more like this</p>

<pre><code>def Stats():
    with open('mbox.txt') as f:
        d = {}
        for line in f:
            if line.startswith('From'):
                words = line.split()
                key = words[3] + " " + words[6]
                if  key in d:
                    d[key] += 1
                else:
                    d[key] = 1
        return d

print(Stats())
</code></pre>

<p>The issues with your code are that you are reusing variable name oops. </p>

<pre><code>words = line.split()
for words in file:
</code></pre>

<p>The original <code>words</code> (the split string) is lost, overwritten by the next line from your file. Which leads to the next error.</p>

<pre><code>for words in file:
</code></pre>

<p>You are iterating over the file again, inside the loop where you are iterating over the file. Not what you intended I'll bet. Instead you probably wanted to remove that loop, it serves no purpose.</p>

<p>Next you want to add to the dict value if the key exists. </p>

<pre><code>if key:
</code></pre>

<p>Won't do that. It just checks that the string isn't <code>None</code> or empty. Instead you want </p>

<pre><code>if key in d:
</code></pre>

<p>Finally you want to add to your total if the key exists, otherwise intialise the value to 1. There is a class <code>defautltdict</code> that could neaten that up a touch. I'll leave it as an exercise to the reader to use it if you want.</p>

<p>hth.</p>

python python-2.7 python-3.x