'How to write dictionary data to csv file?
I have a dictionary like this. I want to write the data inside to csv file but I will run my code over and over again. How can I make it write headers only once? How can I remove the spaces between the lines?
My code
import csv
dl = {7: {'id': 11, 'name': 'Abc', 'age': 35},
25: {'id': 28, 'name': 'refd', 'age': 88},
15: {'id': 45, 'name': 'dfgd', 'age': 20}}
id_list = [7, 25, 15]
def to_csv(data):
fieldnames = ['id', 'name', 'age']
with open('data.csv', 'a+') as f:
dict_writer = csv.DictWriter(f, fieldnames = fieldnames)
dict_writer.writeheader()
dict_writer.writerow(data)
for i in id_list:
to_csv(dl[i])
for empty lines solution is
with open('data.csv', newline='', 'a+') as f:
first rub output:

second run output:

Solution 1:[1]
How about passing a value to your function to indicate whether or not the headers should be written? Something like this:
def to_csv(data, writeheader):
fieldnames = ['id', 'name', 'age']
with open('data.csv', 'a+') as f:
dict_writer = csv.DictWriter(f, fieldnames = fieldnames)
if writeheader:
dict_writer.writeheader()
dict_writer.writerow(data)
id_list = [7,25,15]
for i in id_list:
to_csv(dl[i], i==id_list[0])
Solution 2:[2]
dict_writer.writeheader() # write the header in your file
dict_writer.writerow(data) # write the data in your file
So instead of looping these two lines, you should only run writeheader once and run the writerow function multiple times.
I will let you figure out the actual implementation
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 | |
| Solution 2 | Ivan Kwong |
