2

I have the following data in a dictionary:

{'323503': [{'name': 'Derek', 'age': '21', 'race': 'white'}, {'name': 'Josh', 'age': '15', 'race': 'white'}, {'name': 'Adam', 'age': '32', 'weight': '180'}],
 '3802': [{'name': 'Abe', 'age': '12', 'weight': '132', 'race': 'black'}, {'name': 'Amy', 'age': '31', 'weight': '180'}],
 '290301': [{'name': 'Sally', 'age': '25'}, {'name': 'Joe', 'age': '18'}]
 }

How can I use Python to export it to a csv file such that the csv file contains:

id, name, age, weight, race
323503, Derek, 21, , white
323503, Josh, 15, , white
323503, Adam, 32, 180,
3802, Abe, 12, 132, black
3802, Amy, 31, 180,
290301, Sally, 25, ,
290301, Joe, 18, ,
0

1 Answer 1

3

First, transform your structure in a list of dictionaries. Something like this (maybe in a more compact fashion):

data = {'323503': [{'name': 'Derek', 'age': '21', 'race': 'white'}, {'name': 'Josh', 'age': '15', 'race': 'white'}, {'name': 'Adam', 'age': '32', 'weight': '180'}],
        '3802': [{'name': 'Abe', 'age': '12', 'weight': '132', 'race': 'black'}, {'name': 'Amy', 'age': '31', 'weight': '180'}],
        '290301': [{'name': 'Sally', 'age': '25'}, {'name': 'Joe', 'age': '18'}]
       }

rows = []
for id_ in data:
    for row in data[id_]:
        row.update({'id': id_})
        rows.append(row)

Then use csv.DictWriter to obtain your csv from rows.

Sign up to request clarification or add additional context in comments.

1 Comment

Note that row.update(...) changes the original dictionary (data)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.