Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a list of integers that is the sum of all the integers from a set of lists in a dict?

Let's assume I have a created a dict that is made up of n keys. Each key is mapped to a list of integers of a consistent length. What I want to make now is a new list that represents the sum of the integers at each point in lists of the dict. To illustrate:

my_dict = {'a': [1, 2, 3, 4], 'b': [2, 3, 4, 5], 'c': [3, 4, 5, 6]}

total_sum_list = []

for key in my_dict.keys():
    total_sum_list += ###some way of adding the numbers together

Expected output:

total_sum_list = [6,9,12,15]

As demonstrated above, I am not sure how to set up this for loop so that I can create a list like total_sum_list. I have tried putting together a list comprehension, but my efforts have not been successful thus far. Any suggestions?

like image 248
Bob McBobson Avatar asked Sep 21 '17 14:09

Bob McBobson


People also ask

How do you sum a list of values in a dictionary?

To sum the values in a list of dictionaries: Use a generator expression to iterate over the list. On each iteration, access the current dictionary at the specific key. Pass the generator expression to the sum() function.

How do you sum an integer in a list in Python?

sum() function in Python Python provides an inbuilt function sum() which sums up the numbers in the list. Syntax: sum(iterable, start) iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers.

How do you sum a dictionary element in Python?

It is pretty easy to get the sum of values of a python dictionary. You can first get the values in a list using the dict. values(). Then you can call the sum method to get the sum of these values.

How do you find the sum of two elements in a list in Python?

Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].


Video Answer


1 Answers

What you need is to transpose the lists so you can sum the columns. So use zip on the dictionary values (keys can be ignored) and sum in list comprehension:

in one line:

total_sum_list = [sum(x) for x in zip(*my_dict.values())]

result:

[6, 9, 12, 15]

How it works:

zip interleaves the values. I'm using argument unpacking to pass the dict values are arguments to zip (like zip(a,b,c)). So when you do:

for x in zip(*my_dict.values()):
    print(x)

you get (as tuple):

(1, 3, 2)
(2, 4, 3)
(3, 5, 4)
(4, 6, 5)

data are ready to be summed (even in different order, but we don't care since addition is commutative :))

like image 175
Jean-François Fabre Avatar answered Sep 18 '22 13:09

Jean-François Fabre