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>Your value <code>x</code> holds a string 'ddd/ccc/etc'. it has not next. <code>next()</code> belongs to the iterator and it used to get next element from the iterator. The correct way to call it is <code>it.next()</code></p>

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

<p>But you will get an exception after you finish to consume all elements in the iterator. So, you need to catch StopIteration exception.</p>

<pre><code>for x in it:
    try:
        line, next_line = x, it.next()
        # do your count logic overhere
    except StopIteration:
        break
</code></pre>

<p><code>dic.update({[line,next_line]: 1})</code> does not work. You will skip possible combinations.</p>

python dictionary iterator generator