Python write multiline data in a column of a single row in csv
<p>I have a json response similar to as  dt1 and i'm writing the json data into CSV with fieldnames NAME, Total and details , below is my code.</p>

<pre><code>dt1 = { u'Name': ABC,
        u'total': 6 ,
        u'Details':{
            u'Subject1': {u'Opted': False, u'value': u'100'},
            u'Subject2': {u'Opted': True, u'value': u'200'},
            u'Subject2': {u'Opted': True, u'value': u'200'}
        }
    }

with open('file.csv', 'w') as csvfile:
    fieldnames =  ['Name', 'Total', 'Details']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    dt2 = dt1.values()[0].keys(
    for key in dt1.keys():
        if dt1[key]['detected'] is True)
            writer.writerow({'NAME': dt1['Name'], 'Total' : dt1['Total'], 'Details': ([key, [dt1[key][scan] for scan in dt2]])})
</code></pre>

<p>and the CSV generates is :</p>

<pre><code>NAME      Total    Detail

ABC       6     Subject1, "[u'Opted': False, u'value': u'100']"
ABC       6     Subject2, "[u'Opted': True, u'value': u'200']"
ABC       6     Subject3, {u'Opted': True, u'value': u'500'}
</code></pre>

<p>I want to write multi line data of details dict into single column as shown below. Name and Total not repeating for every subject. Is it possible to do? how do I achieve it.</p>

<pre><code>NAME    Total    Details  
ABC       6     Subject1, "[u'Opted': False, u'value': u'100']"
                Subject2, "[u'Opted': True, u'value': u'200']"
                Subject3, {u'Opted': True, u'value': u'500'}
</code></pre>

<p>try something like this:</p>

<pre><code>import csv

dt1 = {
    u'Name': 'ABC',
    u'Total': 6 ,
    u'Details':{
        u'Subject1': {u'Opted': False, u'value': u'100'},
        u'Subject2': {u'Opted': True, u'value': u'200'},
        u'Subject3': {u'Opted': True, u'value': u'200'}
        }
    }

with open('file.csv', 'w') as csvfile:
    fieldnames =  ['Name', 'Total', 'Details']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()

    first_detail = True
    for k in dt1['Details']:
        if first_detail:
            writer.writerow({'Name': dt1['Name'], 'Total' : dt1['Total'],
                             'Details': k + ',' + str(dt1['Details'][k])})
            first_detail = False
        else:
            writer.writerow({'Name': None, 'Total' : None,
                             'Details': k + ', ' + str(dt1['Details'][k])})
</code></pre>

<p><strong>file.csv:</strong></p>

<pre><code>Name,Total,Details
ABC,6,"Subject3, {'value': '200', 'Opted': True}"
,,"Subject2, {'value': '200', 'Opted': True}"
,,"Subject1, {'value': '100', 'Opted': False}"
</code></pre>

python json csv dictionary