从列表中提取整个Python词典并导出到csv

时间:2018-11-18 12:39:43

标签: python dictionary

我在Python的列表中嵌入了一个字典。我只想提取字典,然后将其导出到一个csv文件,每列代表一个唯一的字典键(即日期)。例如,这是我所拥有的嵌入式词典的一小段:

[[{'Date': '2018-069', 'Title': 'The Effect of Common Ownership on Profits : Evidence From the U.S. Banking Industry', 'Author': 'Jacob P. Gramlich & Serafin J. Grundl'}, {'Date': '2018-068', 'Title': 'The Long and Short of It : Do Public and Private Firms Invest Differently?', 'Author': 'Naomi E. Feldman & Laura Kawano & Elena Patel & Nirupama Rao & Michael Stevens & Jesse Edgerton'}]]

对此将提供任何帮助!

1 个答案:

答案 0 :(得分:0)

应该使用DictWriter,如Patrick在评论中所述

import csv


def main():
    '''The Main'''

    data = [[{'Date': '2018-069', 'Title': 'The Effect of Common Ownership on Profits : Evidence From the U.S. Banking Industry', 'Author': 'Jacob P. Gramlich & Serafin J. Grundl'}, {'Date': '2018-068', 'Title': 'The Long and Short of It : Do Public and Private Firms Invest Differently?', 'Author': 'Naomi E. Feldman & Laura Kawano & Elena Patel & Nirupama Rao & Michael Stevens & Jesse Edgerton'}]]
    with open('sample.csv', 'w', newline='') as csvfile:
        fieldnames = data[0][0].keys()
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

        writer.writeheader()
        for row in data[0]:
            writer.writerow(row)


if __name__ == '__main__':
    main()