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
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.)
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 = {}
for i in categories:
for p in i.ledger:
if p["amount"] < 0:
withdrawn_per_category[i.name] = withdrawn_per_category.get(i.name, 0) - p["amount"]