'How to group csv in python without using pandas

I have a CSV file with 3 rows: "Username", "Date", "Energy saved" and I would like to sum the "Energy saved" of a specific user by date.

enter image description here

For example, if username = 'merrytan', how can I print all the rows with "merrytan" such that the total energy saved is aggregated by date? (Date: 24/2/2022 Total Energy saved = 1001 , Date: 24/2/2022 Total Energy saved = 700)

I am a beginner at python and typically, I would use pandas to resolve this issue but it is not allowed for this project so I am at a complete loss on where to even begin. I would appreciate any help and guidance. Thank you.



Solution 1:[1]

I would turn your CSV file into a two-level dictionary, with username and then date as the keys

infile = open("data.csv", "r").readlines()
savings = dict()

# Skip the first line of the CSV, since that has the column names
# not data
for row in infile[1:]:
    username, date_col, saved = row.strip().split(",")
    saved = int(saved)
    if username in savings:
        if date_col in savings[username]:
            savings[username][date_col] = savings[username][date_col] + saved
        else:
            savings[username][date_col] = saved
    else:
        savings[username] = {date_col: saved}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 James McPherson