Python Nested List Comprehension Error
<p>I'm trying to convert a normal nested iteration into a nest list comp and I'm having trouble.</p>

<pre><code>for k in r.json()['app_list']:
    for i in titles:
        if k['name'] == i['name'] and k['platform'] == i['platform']:
            array.append(session.get(k['api_url'], headers=headers).json())
return array
</code></pre>

<p>Works fine, however</p>

<pre><code>return [session.get(k['api_url'], headers=headers).json()
        for i in titles for k in r.json()
        if k['name'] == i['name'] and k['platform'] == i['platform']]
</code></pre>

<p>throws this error</p>

<pre><code>if k['name'] == i['name'] and k['platform'] == i['platform']]
TypeError: string indices must be integers
</code></pre>

<p>You have your nesting order wrong and you forgot to get the <code>'app_list'</code> key from the <code>r.json()</code> dictionary.</p>

<p>List comprehension loops are still listed in the same order, left to right as you nest them. In other words, use the <em>same order</em> as your original nested <code>for</code> statements:</p>

<pre><code>return [session.get(k['api_url'], headers=headers).json()
        for k in r.json()['app_list']
        for i in titles
        if k['name'] == i['name'] and k['platform'] == i['platform']]
</code></pre>

<p>The above was reached simply by putting everything in the <code>array.append()</code> call <em>at the front</em>, then removing the <code>:</code> colons from the <code>for</code> and <code>if</code> statements and putting the result inside <code>[...]</code> square brackets.</p>

<p>You forgot the <code>['app_list']</code> subscription to the <code>r.json()</code>, and that's the actual cause of the exception; <code>r.json()</code> produces a dictionary, so each <code>k</code> was bound to a <em>key</em> from that dictionary, making the <code>k['name']</code> subscription fail.</p>

python list-comprehension