Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python sum up array based on key

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]]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading