create multidimensional dictionary to count word occurence
<p>I have a source.txt file consisting of words. Each word is in a new line.</p>

<pre><code>apple
tree
bee
go
apple
see
</code></pre>

<p>I also have a taget_words.txt file, where the words are also in one line each.</p>

<pre><code>apple
bee
house
garden
eat
</code></pre>

<p>Now I have to search for each of the target words in the source file. If a target word is found, e.g. apple, a dictionary entry for the target word and each of the 3 preceding and 3 following words should be made. In the example case, that would be</p>

<pre><code>words_dict = {'apple':'tree', 'apple':'bee', 'apple':'go'}
</code></pre>

<p>How can I tell python by creating and populating the dictionary to consider these 3 words before and after the entry in the source_file? 
My idea was to use lists but ideally the code should be very efficient and fast as the files consists of some million words. I guess, with lists, the computation is very slow. </p>

<pre><code>from collections import defaultdict 

words_occ = {}
defaultdict = defaultdict(words_occ)
with open('source.txt') as s_file, open('target_words.txt') as t_file:
    for line in t_file:
        keys = [line.split()]
    lines = s_file.readlines()
    for line in lines:
        s_words = line.strip()
        # if key is found in s_words
        # look at the 1st, 2nd, 3rd word before and after 
        # create a key, value entry for each of them         
</code></pre>

<p>Later, I have to count the occurrence of each key, value pair and add the number to a separate dictionary, that is why I started with a defaultdict.</p>

<p>I would be glad about any suggestion for the above code.</p>

<p>The first issue you will face is your lack of understanding of dicts. Each key can occur only once, so if you ask the interpreter to give you the value of the one you gave you might get a surprise:</p>

<pre><code>&gt;&gt;&gt; {'apple':'tree', 'apple':'bee', 'apple':'go'}
{'apple': 'go'}
</code></pre>

<p>The problem is that there can only be one value associated with the key <code>'apple'</code>.</p>

<p>You appear to be searching for suitable data structures, but StackOverflow is for improving or fixing problematic code.</p>

python dictionary multidimensional-array counter