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

I have a 2d list of strings and numbers. I want to get the sum of all numbers that have the same string. Code is in python

I have a list the contains names and numbers. And for all items with the same name in the list I want to calculate the sum of those numbers.

Please note, I cannot use the numpy function.

This is my 2d list:

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

list = [(‘apple’, 3), (‘apple’, 4), (‘apple’, 6), (‘orange’, 2), (‘orange’, 4), (‘banana’, 5)]

And then adding up the numbers with the same name the expected output is below.

expected output:

apple: 13
orange: 6
banana: 5

>Solution :

Using a simple loop and dict.get:

l = [('apple', 3), ('apple', 4), ('apple', 6),
     ('orange', 2), ('orange', 4), ('banana', 5)]

d = {}
for key, val in l:
    d[key] = d.get(key, 0) + val

print(d)

Output: {'apple': 13, 'orange': 6, 'banana': 5}

For a formatted output:

for key, val in d.items():
    print(f'{key}: {val}')

Output:

apple: 13
orange: 6
banana: 5
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