How to make a nested for loop using a generator in python?
<p>I'm trying to convert this nested for loop:</p>

<pre><code>        for k,v in all_R.iteritems():
            for pairs in v:
                print pairs[1]
</code></pre>

<p>to a one liner, something like this:</p>

<pre><code>print ([pairs[1] for pairs in v for k,v in all_R.iteritems()])
</code></pre>

<p>But I'm getting this error:</p>

<pre><code>    UnboundLocalError: local variable 'v' referenced before assignment
</code></pre>

<p>all_R is a defaultdict where every value has keys that are pairs, and I'm interested in just one value from that pair:</p>

<pre><code>     {'1-0002': [('A-75G', 'dnaN'), ('I245T', 'recF'),... ], '1-0004': [('A-75G', 'dnaN'), ('L161', 'dnaN'),...]}
</code></pre>

<p>List comprehensions are written in the same order as for loops, so you are actually looking for (Note the order is reversed)
<code>print ([pairs[1] for k,v in all_R.iteritems() for pairs in v ])</code></p>

<p>If you are looking to use generators as your title suggests, you can use parenthesis instead of brackets
<code>(pairs[1] for k,v in all_R.iteritems() for pairs in v)</code></p>

<p>That will create a generator with your desired properties.  </p>

python syntax nested generator bioinformatics