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><code>line</code>, like all <code>strs</code>, is an iter<strong>able</strong>, which means it has an <code>__iter__</code> method. But <code>next</code> works with iter<strong>ators</strong>, which have a <code>__next__</code> method (in Python 2 it's a <code>next</code> method). When the interpreter executes <code>next(line)</code>, it attempts to call <code>line.__next__</code>. Since <code>line</code> does not have a <code>__next__</code> method it raises <code>TypeError: str object is not an iterator</code>. </p>

<p>Since <code>line</code> is an iter<strong>able</strong> and has an <code>__iter__</code> method, we can set <code>it = iter(line)</code>. <code>it</code> is an iter<strong>ator</strong> with a <code>__next__</code> method, and <code>next(it)</code> returns the next character in <code>line</code>. But you are looking for the next line in the file, so try something like:</p>

<pre><code>from collections import defaultdict

dic = defaultdict(int)
with open('file.txt') as f:
    content = f.readlines()
    for i in range(len(content) - 1):
        key = content[i].rstrip() + ',' + content[i+1].rstrip()
        dic[key] += 1

for k,v in dic.items():
    print(k,':',v)
</code></pre>

<p><strong>Output</strong> (<em>file.txt</em> as in OP)</p>

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

python dictionary iterator generator