'Write a dictionary which has a list as values into a csv while preserving the list order, my code does this but not separating the values in the rows
I have a dictionary which contains two values as the values of the key (a series of averages in the 50% and 100% order), I want to write them to a csv which will have 3 columns - the key, the 50% average, and the 80% average.
mydict = {230: [5.93, 5.9350000000000005],
235: [5.96, 6.005],
240: [5.970000000000001, 5.985],
245: [6.005, 6.0],
250: [5.98, 5.99],
255: [5.995, 6.015],
260: [6.05, 6.03],
265: [6.02, 6.035],
270: [5.995, 5.984999999999999]}
headers = ["Freq", "50%_average", "100%_average"]
Code which writes the dict but there is no separator
def make_text_file(filepath, list_of_headers):
headers = list_of_headers
with open(filepath, 'w', newline='') as filey:
csv_writer = csv.writer(filey, delimiter='\t', lineterminator='\r\n')
csv_writer.writerow(headers)
filey.close()
def write_results_to_textfile(filepath, results_line):
with open(filepath, 'a', newline='') as filey:
csv_writer = csv.writer(filey, delimiter='\t', lineterminator='\r\n')
csv_writer.writerow(results_line)
def write_averages_to_csv(mydict, headers):
filepath = "mydata.csv"
make_text_file(filepath, headers)
for k, v in mydict.items():
results_line = [k, v[0], v[1]]
write_results_to_textfile(filepath, results_line)
def write_results_to_csv(filepath, results_line):
with open(filepath, '', newline='') as filey:
csv_writer = csv.writer(filey, delimiter='\t', lineterminator='\r\n')
csv_writer.writerow(results_line)
write_averages_to_csv(mydict, headers)
Desired output csv
"Freq", "50%_average", "100%_average",
230, 5.93, 5.935,
235, 5.96, 6.005,
...
270, 5.995, 5.9849
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
