Hello! I am trying to subtract an integer-variable with all values in my dictionary. I've even tried converting the dict to a list. Nothing seems to work for me.
I tried doing this just so see if it works, and it does work for one item in my expenses-dictionary, but how do I get all values from the dictionary and subtract it with my budget?
budget = budget - expenses["Rent"]
The error I'm getting: TypeError: unsupported operand type(s) for -: 'int' and 'str'
CodePudding user response:
So you have a dict called expenses
. Unfortunately, its entries are strings.
The easiest thing to do is
budget -= sum(float(v) for k, v in expenses.items())
where we iterate over all entries of expenses
, turn their values into a float (which bears problems on its own when using it with monetary values, but I do so for simplicity), sum them together and subtract this sum from the budget.
CodePudding user response:
budget = ...
expenses = {...}
for expense in expenses:
budget -= float(expenses[expense])