How To Store The Total Withdrawal Amount For Each Category Object?
I have a Category class and there is a ledger attribute for each instance of this class. This ledger attribute is actually a list of dictionaries which contain the withdrawal and d
Solution 1:
Use a collections.defaultdict
to make aggregations such as that easy as pie.
import collections
# ...
withdrawn_per_category = collections.defaultdict(int)
for i in categories:
for p in i.ledger:
if p["amount"] < 0:
withdrawn_per_category[i.name] += -p["amount"]
(I've opted to use int
as the default data type, but it doesn't truly matter here, so long as it's a conversible numeric type.)
Without collections
If for some reason you don't want to use the handy, built-in collections
module, you can emulate the same behavior yourself with a regular dict:
withdrawn_per_category = {}
foriin categories:
forpin i.ledger:
if p["amount"] < 0:
withdrawn_per_category[i.name] = withdrawn_per_category.get(i.name, 0) - p["amount"]
Post a Comment for "How To Store The Total Withdrawal Amount For Each Category Object?"