Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Data Science by (18.4k points)
edited by

For example, I have the dictionary 1:

dict1 = {"a":[0, 0, 0, 0, 0, 1, 3, 6], "b":[1, 4, 6, 0], "c":[4, 6, 7, 8, 0, 9]}

I want to create a new array which looks something like this:

array = [5, 10, 13, 8, 0, 10, 3, 6]

which each index inside the new array is the sum of the same position in each key in a dictionary.

1 Answer

0 votes
by (36.8k points)
edited by

Using zip() is a standard way to match up  the items like this. However, zip() will stop at some shortest element you are zipping, so you won't get all those values you want. For this, you can use itertools.zip_longest() with the fillvalue or 0:

from itertools import zip_longest

dict1 = {"a":[0, 0, 0, 0, 0, 1, 3, 6], "b":[1, 4, 6, 0], "c":[4, 6, 7, 8, 0, 9]}

[sum(nums) for nums in zip_longest(*dict1.values(), fillvalue=0)]

# [5, 10, 13, 8, 0, 10, 3, 6]

You want to know more about Data Science the do check out the Data Science course

Browse Categories

...