Home > Back-end >  How to create a CSV table using python dictionary without using any modules or imports
How to create a CSV table using python dictionary without using any modules or imports

Time:03-20

I have this dictionary that takes data from a csv file:

def read_results(full_file_path):
    csv_dict = {}
    with open(full_file_path,'r') as t:
        table = t.readlines()[1:]
        for line in table:
            line = line.replace('\n', '')
            line = line.split(',')
            line = list(map(float, line))
            key = (line[1], line[3])
            if key in csv_dict:
                csv_dict[key].append((line[4], line[5], line[6]))
            else:
                csv_dict[key] = [(line[4], line[5], line[6])]
        return csv_dict


#that looks like this:
{(1.0, 3.0): [(602.0, 1661.0, 0.0), (945.0, 2164.0, 0.0), (141.0, 954.0, 0.0), (138.0, 913.0, 0.0),....}

but now i need to make use of this dictionary to create a csv of my own that needs to calculate the mean of each value row to its corresponding key couple like this:

 c     b     first     finish     fix/ext 
1     3     744.67     1513.67     0.67 
0.8     3     88     858.67     0.67 
0.8     1.5     301.5     984.5     0.5 
1     1.5     419     844.5     0 

and i cant use any outside libraries or modules, what i tried until now :

def Summarize_res(results):
    with open('summary_results.csv', 'w', newline='') as f:
        header = ['c','b','first','finish','fix/ext']
        f.write(str(header))
        for line in dict:
            first = sum(line[4])/len(line[4])
            finish = sum(line[5])/len(line[6])
            fix_ext = sum(line[5])/len(line[6])

CodePudding user response:

I'm not sure if that is what you want exactly, but here for every key it will find a mean of the corresponding values of the tuples and write it in the file. The code can definitely be simplified, but I didn't have much time for it, sorry.

def Summarize_res(dict):
    with open('summary_results.csv', 'w') as f:
        header = ['c','b','first','finish','fix/ext']
        f.write(','.join(str(e) for e in header))
        f.write("\n")
        for key in dict:
            key1, key2 = key
            first_arr = []
            finish_arr = []
            fix_arr = []
            for element in dict[key]:
                first, finish, fix = element
                first_arr.append(first)
                finish_arr.append(finish)
                fix_arr.append(fix)
            first_final = sum(first_arr) / len(first_arr)
            finish_final = sum(finish_arr) / len(finish_arr) 
            fix_final = sum(fix_arr) / len(fix_arr)
            result = [key1, key2, first_final, finish_final, fix_final]
            f.write(','.join(str(e) for e in result))
            f.write("\n")

Summarize_res(dict)

This part can be just inserted to your previous code and it should work.

  • Related