-1

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.

M. ahmed
  • 53
  • 2
  • 11

2 Answers2

0

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)

0

You could do this pandas quite easily

import pandas as pd
# read in the csv
# group by the date column, and sum the other columns
# reset index to get the dates as a series
# convert dataframe to dictionary
out = pd.read_csv('file.csv').groupby('date').sum().reset_index().to_dict('records')

#Out I
[{'date': '26-03-2020', 'marks': 2796, 'course1': 2157},
 {'date': '27-03-2020', 'marks': 2212, 'course1': 1783}]

# Out II
# if you insist on having it as a dict of dicts
out = {k['date']: {'marks': k['marks'], 'course1': k['course1']} for k in out }

{
    '26-03-2020': {'marks': 2796, 'course1': 2157},
     '27-03-2020': {'marks': 2212, 'course1': 1783}
}

Further explanation for clarity

It is not possible to have a dictionary the way that you are asking for. My example above shows that the date is the key to a new dictionary. In your example you are using a , instead of a :, which is not possible.

Philip
  • 944
  • 11
  • 26