-1

I am using for loop to go through the list like:

for c in classes:
    print(c.get(‘class’), c.get('plan'), c.get('type'), c.get(‘money’,{})[0].get(‘totalspent’))

I get results:

class1   plan1  type1 10
class2   plan2  type2 20
class3   plan3  type3 10
class2   plan2  type2 30
class3   plan3  type3 20 

I am trying to figure out a way to get something like:

class1  plan1 type1 10
class2  plan2 type2 50
class3  plan3 type3 30

is there an easier way to achieve this?

Mazdak
  • 105,000
  • 18
  • 159
  • 188
NoviceMe
  • 3,126
  • 11
  • 57
  • 117
  • Also, https://stackoverflow.com/questions/47055259/python-dict-group-and-sum-multiple-values – Mazdak Mar 08 '19 at 21:35

1 Answers1

-1

Just figured it as soon as I made a post. Maybe will help someone else in the future:

from collections import defaultdict

output = defaultdict(int)

for c in classes:
    output[c.get('class'), c.get('plan'), c.get('type')] += c.get('money', {})[0].get('totalspent', 0)
NoviceMe
  • 3,126
  • 11
  • 57
  • 117