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

Question:

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
Asked By: Marcus Availo

||

Answers:

One way is to use default dict:

from collections import defaultdict

d = defaultdict(list)  # all elements in the dictionary will be a list by default

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

for name, number in l:
    d[name].append(number)
for key, value in d.items():
    print(f"{key}: {sum(value)}")

Or directly:

from collections import defaultdict

d = defaultdict(float)  # 

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

for name, number in l:
    d[name] += number
print(d)

by the way, list is a keyword in python so it is "bad" behavior to overwrite them.

Answered By: 3dSpatialUser

You can iterate on this list, and use a dict to count all the fruits:

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

final_dict = {}

for fruit, count in list:
    if fruit not in final_dict:
        final_dict[fruit] = count
    else:
        final_dict[fruit] += count
        
print(final_dict)

Outputs:

{'apple': 13, 'orange': 6, 'banana': 5}
Answered By: Antoine Delia

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
Answered By: mozway
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.