Search code examples
pythonstringlistsum2d

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:

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