简体   繁体   中英

how to convert dictionary into csv file

I got some data and I need to convert it into a csv file. I'm not a coder but I think that python can help me with these dict/tuples.

a = {
 'page': '1',
 'records': 984,
 'rows': [{'cell': ['2012000000885',
                    'A. B. OLIVEIRA - ME',
                    '10\\/08\\/2012',
                    '2.200,00',
                    '0,00',
                    '0,00'],
           'id': '2012000000885;02070712000102;2012;4'},
          {'cell': ['2012000000440',
                    'A. C SILVA E CIA LTDA',
                    '26\\/04\\/2012',
                    '600,00',
                    '600,00',
                    '600,00'],
           'id': '2012000000440;02070712000102;2012;4'},
          {'cell': ['2012000000104',
                    'ADAILTON PEREIRA DE OLIVEIRA',
                    '27\\/01\\/2012',
                    '100,00',
                    '100,00',
                    '100,00'],
           'id': '2012000000104;02070712000102;2012;4'},
          {'cell': ['2012000000261',
                    'ADAILTON PEREIRA DE OLIVEIRA',
                    '01\\/03\\/2012',
                    '200,00',
                    '200,00',
                    '200,00'],
           'id': '2012000000261;02070712000102;2012;4'},
          {'cell': ['2012000000360',
                    'ADAILTON PEREIRA DE OLIVEIRA',
                    '28\\/03\\/2012',
                    '200,00',
                    '200,00',
                    '200,00'],
           'id': '2012000000360;02070712000102;2012;4'}],
 'total': 1}   

I'm interest just on 'rows', I need separate 'Id' an 'cell' to import them to csv file. Thank you in advance for any help.

Rogerio Marinho

import csv
with open('output.csv', 'wb') as fout:
    csvout = csv.writer(fout)
    for row in a['rows']:
        csvout.writerow( [row['id']] + row['cell'] )

Creates a CSV file with first column as ID and subsequent columns as whatever cell is.

This is much cleaner:

import csv
with open('names.csv', 'w') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM