Home > front end >  Write a dictionary which has a list as values into a csv while preserving the list order, my code do
Write a dictionary which has a list as values into a csv while preserving the list order, my code do

Time:02-25

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

CodePudding user response:

You can use pandas:

import pandas as pd

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"]

df = pd.DataFrame.from_dict(mydict,orient='columns') 
df = df.T
df.reset_index(inplace=True)
df.columns = headers
df.to_csv (r'file.csv', index = False, header=True)

Output :

   Freq  50%_average  100%_average
   230        5.930         5.935
   235        5.960         6.005
   240        5.970         5.985
   245        6.005         6.000
   250        5.980         5.990
   255        5.995         6.015
   260        6.050         6.030
   265        6.020         6.035
   270        5.995         5.985
  • Related