如何将字典转换为csv文件

时间:2012-10-20 14:44:26

标签: python list dictionary tuples

我收到了一些数据,我需要将其转换为csv文件。我不是编码器,但我认为python可以帮助我使用这些dict /元组。

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}   

我对“行”感兴趣,我需要单独的“Id”和“单元格”将它们导入到csv文件中。 提前感谢您的帮助。

Rogerio Marinho

2 个答案:

答案 0 :(得分:4)

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

创建一个CSV文件,第一列为ID,后续列为任何单元格。

答案 1 :(得分:0)

这更清洁:

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