Home > database >  Summing up dict values instead of overwriting them Python
Summing up dict values instead of overwriting them Python

Time:10-08

I am new to coding/progamming and I can't wrap my brain around summing up values within a dictonary.

So here is what I want to achieve: I have a CSV file with products being bought with the following data:

Example:

id,product_name,buy_date,buy_price,quantity,exp_date
1,apple,2022-01-26,0.8,38,2022-01-10
2,apple,2022-01-26,0.8,71,2022-01-10
3,banana,2022-01-26,0.8,62,2022-01-10
4,banana,2022-01-26,0.8,51,2022-01-10
5,grape,2022-01-26,1,45,2022-01-10
6,grape,2022-01-26,1,31,2022-01-10

From this csv I want to store the amount of products when the exp date has been met in a dict.

So far this is my code:

expired_dict ={}
with open("bought.csv", "r") as File:
for row in csv.DictReader(File):
    if today() > row["exp_date"]:            
        expired_dict.update({row["product_name"]:[row["quantity"]]})

Output:
{'apple': ['71'], 'banana': ['51'], 'grape': ['31']}

So far this works for storing only the products, but as you can see it will update the quantity as well to the last row. But I need to add those values, not replace them. How can I build this in?

CodePudding user response:

You need to add the value in the current row of the CSV to the corresponding dictionary value.

This is a good use of collections.defaultdict(), it will create the dictionary element if it doesn't exist yet.

import collections

expired_dict = collections.defaultdict(int)

with open("bought.csv", "r") as File:
    for row in csv.DictReader(File):
        if today() > row["exp_date"]:            
            expired_dict[row["product_name"]]  = int(row["quantity"])

print(expired_dict)

CodePudding user response:

    expired_dict ={}
    with open("bought.csv", "r") as File:
    for row in csv.DictReader(File):
        if today() > row["exp_date"]:            
            if(row["product_name"] in expired_dict:
             expired_dict[row["product_name"]] = expired_dict[row["product_name"]]  int(row["quantity"])
            else:
             expired_dict[row["product_name"]] = int(row["quantity"])

You can change your code as above then if key exist values get add.

  • Related