【问题标题】:Turning a list full of dictionaries into a csv file in Python [duplicate]在Python中将一个充满字典的列表转换为一个csv文件[重复]
【发布时间】:2018-08-25 16:18:00
【问题描述】:

我目前正在尝试打开这个字典列表

[
        {'John Guy': [28, '03171992', 'Student']},
        {'Bobby Jones': [22, '02181982', 'Student']},
        {'Claire Eubanks': [18, '06291998', 'Student']},
]

写入 csv 文件,但标题包含姓名、年龄、出生日期和职业。有没有人有任何想法?我似乎无法让它与 csv 作家一起工作。谢谢。

【问题讨论】:

标签: python list csv dictionary


【解决方案1】:

你可以试试这个:

import csv
d = [
    {'John Guy': [28, '03171992', 'Student']},
    {'Bobby Jones': [22, '02181982', 'Student']},
    {'Claire Eubanks': [18, '06291998', 'Student']},
]
new_d = [i for b in [[[a]+b for a, b in i.items()] for i in d] for i in b]
with open('filename.csv', 'a') as f:
   write = csv.writer(f)
   write.writerows([['Name', 'Age', 'DOB', 'Occupation']]+new_d)

输出:

Name,Age,DOB,Occupation
John Guy,28,03171992,Student
Bobby Jones,22,02181982,Student
Claire Eubanks,18,06291998,Student

【讨论】:

    【解决方案2】:

    您需要做的就是遍历每个字典,获取名称,然后使用该名称获取列表中的其他三项内容。您甚至不需要使用 csv 库,因为它非常简单。

    data = [
            {'John Guy': [28, '03171992', 'Student']},
            {'Bobby Jones': [22, '02181982', 'Student']},
            {'Claire Eubanks': [18, '06291998', 'Student']},
    ]
    
    f = open("data.csv", "w")
    f.write("Name,Age,DOB,Job\n")
    
    for person in data:
        for name in person:
            f.write(name)
            for i in range(3):
                f.write("," + str(person[name][i]))
            f.write("\n")
    f.close()
    

    【讨论】:

      【解决方案3】:

      这是通过pandasitertools.chain 提供的一种解决方案。

      from itertools import chain
      import pandas as pd
      
      lst = [ {'John Guy': [28, '03171992', 'Student']},
              {'Bobby Jones': [22, '02181982', 'Student']},
              {'Claire Eubanks': [18, '06291998', 'Student']}
            ]
      
      res = [[name] + list(*details) for name, *details in \
             chain.from_iterable(i.items() for i in lst)]
      
      df = pd.DataFrame(res, columns=['Name', 'Age', 'DOB', 'Occupation'])
      
      df.to_csv('file.csv', index=False)
      

      【讨论】:

        猜你喜欢
        • 2012-09-24
        • 2017-12-04
        • 2021-04-01
        • 2016-09-14
        • 2021-12-22
        • 2018-12-13
        • 2018-01-06
        • 2018-01-14
        • 2014-03-01
        相关资源
        最近更新 更多