Home > Back-end >  Python sum up array based on key
Python sum up array based on key

Time:12-02

What is the best way to sum up based on the key parameter

E.g.

x  = [[0,"xxx",100],[1,"yyy",100],[1,"xxx",100]]

How to sum up .. to make it [[0,"xxx",200],[1,"yyy",100]]

So the first label in the list will be the main one and all the rest will be summed up.

Looking for something easy (as all my ideas went into the mess...)

  • ANy hints, ideas, examples will be appreciated

CodePudding user response:

I think you actually want something like this:

x  = [[0,"xxx",100],[1,"yyy",100],[1,"xxx",100]]

result={}
for item in x:
    result[item[1]] = result.get(item[1], 0)   item[2]

print(result)
  • Related