'How to push Nested Dict Data to csv file in python?
I am trying to create a csv file from the data below using python3:-
I am recicving the data in this dict format from a for loop :-
data = [{('Apr', 'Apurv'): 10, ('Mar', 'Apurv'): 58}, {('Apr', 'Smriti'): 12, ('Mar', 'Smriti'): 70}, {('Apr', 'Pankhuri'): 12, ('Mar', 'Pankhuri'): 73}, {('Apr', 'Parth'): 21, ('Mar', 'Parth'): 101}]
I need fetch the header and rows from data so that i can push data to csv.
header = ["Name", 'Apr', 'March'] # This could be more depending on the months present in data
And row should be like :
row1 = ["Apurv", 10, 58]
row2 = ["Smriti", 12, 70]
row3 = ["Pankhuri, 12, 73]
row4 = ["Parth", 21, 103]
rows = [row1, row2, row3, row4]
with open("smriti.csv", 'w') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(header)
csvwriter.writerow(rows)
I need to put each name and month as different columns and insert the rows with respective name and count values corresponding to it.
The output should look like this :-
I am trying to use csv library in python.
Can anybody suggest how i can do this ?
Solution 1:[1]
Here is a code to help you experiment with:
import csv
data = [{('Apr', 'Apurv'): 10, ('Mar', 'Apurv'): 58},
{('Apr', 'Smriti'): 12, ('Mar', 'Smriti'): 70},
{('Apr', 'Pankhuri'): 12, ('Mar', 'Pankhuri'): 73},
{('Apr', 'Parth'): 21, ('Mar', 'Parth'): 101}]
header = ["Name"]
result = []
for item in data:
line = {}
for index, element in enumerate(item):
# Collect header elements
if element[0] not in header:
header.append(element[0])
# Fill table content
if index == 0:
line["Name"] = element[1]
line[element[0]] = item[element[0], element[1]]
if index == 1:
result.append(line)
# Double-check the data
print(header)
print(result)
# Create the csv file
with open('smriti.csv', 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=header)
writer.writeheader()
writer.writerows(result)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dan Constantinescu |

