Home > Back-end >  How to selects items by argument and sums them in another function
How to selects items by argument and sums them in another function

Time:12-11

Hi I basically have example how Write a program to track family income and expenses. So I need to 2 functions one that adds items into seznam ok I did that. 2 functions that selects items by argument and sums them.

How to add second function without errors def overview(month, year) and sum every category from function one to second by only month and year

its always show some error.

result should be something like this print(overview(11,2022)) Prints {'food': 750, 'household': 150, 'housing': 300}

listof_items = {}
def add_item(day,month,year,amount,category):

  listof_items ={day,month,year,amount,category}
  print(listof_items )
   

  
add_item(15,10,2022,150,"food")
add_item(16,11,2022,250,"food")
add_item(17,11,2022,300,"housing")
add_item(18,11,2022,500,"food")
add_item(16,11,2022,150,"housing")

I try to put second function but that will never work I dont know how to get items from the list to sum them only by month and year from function 1

CodePudding user response:

Try:

def add_item(lst, day, month, year, amount, category):
    lst.append(
        {
            "day": day,
            "month": month,
            "year": year,
            "amount": amount,
            "category": category,
        }
    )


def overview(lst, month, year):
    out = {}
    for d in lst:
        if d["month"] == month and d["year"] == year:
            out.setdefault(d["category"], []).append(d["amount"])

    return {k: sum(v) for k, v in out.items()}


listof_items = []

add_item(listof_items, 15, 10, 2022, 150, "food")
add_item(listof_items, 16, 11, 2022, 250, "food")
add_item(listof_items, 17, 11, 2022, 300, "housing")
add_item(listof_items, 18, 11, 2022, 500, "food")
add_item(listof_items, 16, 11, 2022, 150, "housing")

print(listof_items)

Prints:

[
    {"day": 15, "month": 10, "year": 2022, "amount": 150, "category": "food"},
    {"day": 16, "month": 11, "year": 2022, "amount": 250, "category": "food"},
    {
        "day": 17,
        "month": 11,
        "year": 2022,
        "amount": 300,
        "category": "housing",
    },
    {"day": 18, "month": 11, "year": 2022, "amount": 500, "category": "food"},
    {
        "day": 16,
        "month": 11,
        "year": 2022,
        "amount": 150,
        "category": "housing",
    },
]

Then:

print(overview(listof_items, 11, 2022))

Prints:

{"food": 750, "housing": 450}
  • Related