将一个完整的字典列表转换为Python中的csv文件

时间:2018-03-16 14:43:01

标签: python list csv dictionary

我目前正在尝试更改此词典列表

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

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

3 个答案:

答案 0 :(得分:1)

您需要做的就是浏览每个字典,获取名称,然后使用该名称获取列表中的其他三个字体。您甚至不需要使用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()

答案 1 :(得分:0)

你可以试试这个:

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 :(得分:0)

这是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)