Python在csv

时间:2016-09-15 11:22:02

标签: python json csv dictionary

我有一个类似于dt1的json响应,我正在将json数据写入CSV,字段名为NAME,Total和details,下面是我的代码。

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]])})

,CSV生成的是:

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'}

我想将详细信息dict的多行数据写入单列,如下所示。名称和总计不会重复每个主题。有可能吗?我该如何实现它。

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'}

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

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])})

<强> FILE.CSV:

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