0

I have a list of dictionaries with identical keys, where the values of each dictionary are NumPy arrays of the same size.

Here's the example

a = {"a": np.array([1,2]),"b": np.array([2,4]),}
b = {"a": np.array([5,7]),"b": np.array([12,34]),}
c = [a,b]

I would like to sum the values(Numpy arrays) for the same keys across all of the dictionaries.

I have tried Counter form collections but it only seems to work for scalar values. I tried to do it with two loops but got confused. I probably can do it with three loops but is there another more elegant way?

Thanks

2 Answers 2

2

Try with:

{k:a[k]+b[k] for k in a.keys()}

Or in general with reduce:

from functools import reduce
reduce(lambda x,y: {k:x[k]+y[k] for k in x.keys()}, c)

Output:

{'a': array([6, 9]), 'b': array([14, 38])}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, the reduce formula worked. It seems slightly unclear to me how it works, but I guess I will check it out. Thanks.
1

You can just use sum() and dict-comprehension:

keys = a.keys()
{k: sum(x[k] for x in c) for k in keys}

This assumes that the keys in a are found in all dicts, otherwise you would need to check for key existence (e.g. sum(x[k] for x in c if k in x)).

The full example reads:

import numpy as np


a = {"a": np.array([1,2]),"b": np.array([2,4]),}
b = {"a": np.array([5,7]),"b": np.array([12,34]),}
c = [a,b]


keys = a.keys()
{k: sum(x[k] for x in c) for k in keys}
# {'a': array([6, 9]), 'b': array([14, 38])}

2 Comments

nice and elegant
keep in mind that reduce() may be faster as one of the loops is in C.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.