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>You could use <a href="http://stackoverflow.com/questions/4406389/if-else-in-a-list-comprehension">conditional list comprehension</a> with <a href="http://docs.python.org/2/library/itertools.html#itertools.chain"><code>itertools.chain</code></a> for those elements which need flattening:</p>

<pre><code>In [54]: import itertools

In [55]: [list(itertools.chain(*l)) if isinstance(l[0], list) else l for l in data]
Out[55]: 
[[{'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