Creating a dictionary of words and their context in a sentence
<p>I have a Python list containing hundreds of thousands of words. The words appear in the order they are in the text.</p>

<p>I'm looking to create a dictionary of each word associated with a string containing that word with 2 (say) words that appear before and after it.</p>

<p>For example the list: "This" "is" "an" "example" "sentence"</p>

<p>Should become the dictionary:</p>

<pre><code>"This" = "This is an"
"is" = "This is an example"
"an" = "This is an example sentence"
"example" = "is an example sentence"
"sentence" = "an example sentence"
</code></pre>

<p>Something like:</p>

<pre><code>WordsInContext = Dict()
ContextSize = 2
wIndex = 0
for w in Words:
    WordsInContext.update(w = ' '.join(Words[wIndex-ContextSize:wIndex+ContextSize]))
    wIndex = wIndex + 1
</code></pre>

<p>This may contain a few syntax errors, but even if those were corrected, I'm sure it would be a hideously inefficient way of doing this.</p>

<p>Can someone suggest a more optimized method please?</p>
