TypeError: str object is not an iterator
<p>I have a file consisting of words, one word on each line. The file looks like this:</p>

<pre><code>aaa
bob
fff
err
ddd
fff
err
</code></pre>

<p>I want to count the frequency of the pair of words which occur one after the other.</p>

<p>For example,</p>

<pre><code>aaa,bob: 1
bob,fff:1
fff,err:2
</code></pre>

<p>and so on.
 I have tried this</p>

<pre><code>f=open(file,'r')
content=f.readlines()
f.close()
dic={}
it=iter(content)
for line in content:
    print line, next(line);
    dic.update({[line,next(line)]: 1})
</code></pre>

<p>I got the error: </p>

<pre><code>TypeError: str object is not an iterator
</code></pre>

<p>I then tried using an iterator:</p>

<pre><code>it=iter(content)
for x in it:
    print x, next(x);
</code></pre>

<p>Got the same error again. 
Please help!</p>

<p>You just need to keep track of the previous line, a file object returns it own iterator so you don't need the <em>iter</em>  or <em>readlines</em> at all, call <em>next</em> once at the very start to creating a variable <em>prev</em> then just keep updating  <em>prev</em> in the loop:</p>

<pre><code>from collections import defaultdict

d = defaultdict(int)

with open("in.txt") as f:
    prev = next(f).strip()
    for line in map(str.strip,f): # python2 use itertools.imap
        d[prev, line] += 1
        prev = line
</code></pre>

<p>Which would give you:</p>

<pre><code>defaultdict(&lt;type 'int'&gt;, {('aaa', 'bob'): 1, ('fff', 'err'): 2, ('err', 'ddd'): 1, ('bob', 'fff'): 1, ('ddd', 'fff'): 1})
</code></pre>

python dictionary iterator generator