-2

I am currently trying to turn this list of dictionaries

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

into a csv file but with a header that includes Name, Age, Date of Birth, and Occupation. Does anyone have any ideas? I can't seem to make it work with the csv writer. Thank you.

BoopityBoppity
  • 929
  • 2
  • 9
  • 11
  • Search for something like "Python json to csv" there are tons of examples of this https://stackoverflow.com/questions/1871524/how-can-i-convert-json-to-csv – Cory Kramer Mar 16 '18 at 14:43

3 Answers3

1

All you need to do is go through each dictionary, get the name, then use the name to get the other three things in the list. You don't even need to use the csv library as it's pretty simple.

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()
dangee1705
  • 3,445
  • 1
  • 21
  • 40
0

You can try this:

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)

Output:

Name,Age,DOB,Occupation
John Guy,28,03171992,Student
Bobby Jones,22,02181982,Student
Claire Eubanks,18,06291998,Student
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0

This is one solution via pandas and itertools.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)
jpp
  • 159,742
  • 34
  • 281
  • 339