从列表中提取整个Python字典并导出到csv
我在Python的列表中嵌入了一个字典。我只想提取字典,然后将其导出到csv文件,每列表示一个唯一的字典键(即日期)。例如,下面是我拥有的嵌入式词典的一个(小片段):从列表中提取整个Python字典并导出到csv,python,dictionary,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. G
[[{'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'}]]
在此方面的任何帮助都将不胜感激 如帕特里克在评论中提到的那样,使用
DictWriter
,应该做下面这样的事情
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()
l[0][0]
?然后将其转换为csv