Search code examples
pythonarraysdictionarykey-value-store

How to add the values of key 1 into another key inside the dictionary to build up an array?


For example I have a dictionary 1:

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

and I want to create a new array 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 the dictionary.


Solution

  • Using zip() is the normal way to match up items like this. However, zip() will stop at the shortest element you are zipping, so you won't get all the values you want. For this, you can use itertools.zip_longest() with a 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]