Home > Blockchain >  I have a 2d list of strings and numbers. I want to get the sum of all numbers that have the same str
I have a 2d list of strings and numbers. I want to get the sum of all numbers that have the same str

Time:11-16

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

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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}
  • Related