【问题标题】:Extract an entire Python dictionary from a list and export to csv [duplicate]从列表中提取整个 Python 字典并导出到 csv [重复]
【发布时间】:2018-11-18 12:39:42
【问题描述】:

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

[[{'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'}]]

对此的任何帮助将不胜感激!

【问题讨论】:

  • l[0][0] ?然后将其转换为 csv

标签: python dictionary


【解决方案1】:

应该像下面这样使用DictWriter,正如 Patrick 在 cmets 中提到的那样

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()

【讨论】:

    猜你喜欢
    • 2020-11-25
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    • 2018-05-06
    • 2021-12-05
    • 2016-09-24
    相关资源
    最近更新 更多