Home > Net >  Sum the values in each inputs
Sum the values in each inputs

Time:03-11

I am trying to get the total value of each variable that's stored in the dictionary. I am a beginner who's struggling with this line of code. Can someone help me figure out the bug?

income_list = { 
    "Job": [],
    "Business": [],
    "Dividends": [],
    "Sideline": [],
    "Others": []

}
total_income = 0
job = income_list["Job"].append(float(input(f"Enter income for job: € ")))
business = income_list["Business"].append(float(input(f"Enter income for Business: € ")))
dividends = income_list["Dividends"].append(float(input(f"Enter income for Dividends: € ")))
sideline = income_list["Sideline"].append(float(input(f"Enter income for Sideline: € ")))
others = income_list["Others"].append(float(input(f"Enter other incomes: € ")))

for value in income_list.values():
 print(sum(value)) 

CodePudding user response:

You can use a list comprehension, given that you need a sum of sums:

total = sum([sum(source) for source in income_list.values()])

This method will work even if your income sources contain multiple values (since they are lists).

The same result can be achieved by giving a generator to sum:

total = sum(sum(source) for source in income_list.values())

CodePudding user response:

you could try something like this :

from itertools import chain

sum(chain(income_list.values())

CodePudding user response:

I think you want one of two things: 1) a list with dictionaries/objects, or 2) a dictionary with lists. I would go with 1) because it feels more intuitive to me, but since it seems you are already trying to achieve 2), I will do that as well.

I will provide a mimimalistic example, and then you should be able to extend it to your program.

my_lists = {
  "list1": [],
  "list2": []
}

my_input = Input()
my_lists["list1"].append(my_input)

for x in my_lists["list1"]:
  print(x)

CodePudding user response:

First, it makes no sense to use a list as the dictionary value if what you want to store is a single value. Second, you need to add to the "total_income" variable in the for loop.

That code works:

income_list = { 
}

total_income = 0
income_list["Job"]=float(input(f"Enter income for job: € "))
income_list["Business"]=float(input(f"Enter income for Business: € "))
income_list["Dividends"]=float(input(f"Enter income for Dividends: € "))
income_list["Sideline"]=float(input(f"Enter income for Sideline: € "))
income_list["Others"]=float(input(f"Enter other incomes: € "))

for value in income_list.values():
    total_income  = value

print(total_income)

That said, I think you don't even need to use a dictionary for that, just simple float variables.

  • Related