How to do List flattening inside the loop with list comprehension?
<p>here i am having list of dictionaries, my goal is to iterate over list and whenever there is 2 or more list available, i want to merge them and append in a output list, and whenever there is only one list it needs to be stored as it as.</p>

<pre><code>data = [
            [[{'font-weight': '1'},{'font-weight': '1'}],[{'font-weight': '2'},{'font-weight': '2'}]],
            [{'font-weight': '3'},{'font-weight': '3'},{'font-weight': '3'}],
            [[{'font-weight': '1'},{'font-weight': '1'}],[{'font-weight': '2'},{'font-weight': '2'}]],
            [{'font-weight': '3'},{'font-weight': '3'}]
        ]
</code></pre>

<p>I can do list flattening for particular element <code>data[0]</code></p>

<pre><code>print([item for sublist in data[0] for item in sublist])
[{'font-weight': '1'}, {'font-weight': '1'}, {'font-weight': '2'}, {'font-weight': '2'}]
</code></pre>

<p>Expected output :</p>

<pre><code>data = [
            [{'font-weight': '1'},{'font-weight': '1'},{'font-weight': '2'},{'font-weight': '2'}],
            [{'font-weight': '3'},{'font-weight': '3'},{'font-weight': '3'}],
            [{'font-weight': '1'},{'font-weight': '1'},{'font-weight': '2'},{'font-weight': '2'}]
            [{'font-weight': '3'},{'font-weight': '3'}]
        ]
</code></pre>

<p>Try this,</p>

<pre><code>result = []
for item in data:
    result.append([i for j in item for i in j])
</code></pre>

<p>Single line code with list comprehension,</p>

<pre><code>[[i for j in item for i in j] for item in data]
</code></pre>

<p>Alternative method,</p>

<pre><code>import numpy as np
[list(np.array(i).flat) for i in data]
</code></pre>

<p><strong>Result</strong></p>

<pre><code>[[{'font-weight': '1'},
  {'font-weight': '1'},
  {'font-weight': '2'},
  {'font-weight': '2'}],
 [{'font-weight': '3'}, {'font-weight': '3'}, {'font-weight': '3'}],
 [{'font-weight': '1'},
  {'font-weight': '1'},
  {'font-weight': '2'},
  {'font-weight': '2'}],
 [{'font-weight': '3'}, {'font-weight': '3'}]]
</code></pre>

python list dictionary