How can I write data from a dictionary to a CSV file in Python
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': 'J开发者_开发知识库oe', '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, ,
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
.
精彩评论