Search code examples
pythonlinuxcsvreader

how to add rows in while reading csv file in python


Here is my csv file:

enter image description here

i want to add the same date values in tuples.

I want the answer like this:

{
    {'26-03-2020', marks:2923,couse1:2297}, 
    {'27-03-2020', marks:2212,course1:1783}
}

Is there are any easy solution for this.or can i do it with using only one loop? thanks in advance.


Solution

  • Try something like the following

    import csv, io
    
    data = '''\
    date,marks,course1
    26-03-2020,1,10
    26-03-2020,2,20
    26-03-2020,4,40
    27-03-2020,100,2
    27-03-2020,200,4
    27-03-2020,400,8
    '''
    
    out = {}
    f = io.StringIO(data)
    reader = csv.DictReader(f)
    for r in reader:
        k = r['date']
        m = int(r['marks'])
        c = int(r['course1'])
        if k in out:
            out[k]['marks'] += m
            out[k]['course1'] += c
        else:
            out[k] = {'marks': m, 'course1': c}
    
    print(out)