SharpObject - 2 months ago 8x

Python Question

I have a dictionary of 1000+ default dicts, I want to iterate through each default dict, sum them up on key and then divide by the count to get the average value per key.

Each default dict has the same keys, i.e.

`{'A': 0.0, 'B': 1.0, 'C': 1.0, 'D': 1.0, 'E': 1.0}`

{'A': 2.0, 'B': 1.2, 'C': 3.0, 'D': 1.0, 'E': 3.0}

I want the following to be my output

`{'A': 1.0, 'B': 1.1, 'C': 2.0, 'D': 1.0, 'E': 2.0}`

How do I iteratively add default dicts up, and then divide them, a la row operations in a DataFrame? Or is there a better way to be doing this?

Thanks

Answer

How about using a dictionary comprehension with `sum`

:

```
d1 = {'A': 0.0, 'B': 1.0, 'C': 1.0, 'D': 1.0, 'E': 1.0}
d2 = {'A': 2.0, 'B': 1.2, 'C': 3.0, 'D': 1.0, 'E': 3.0}
dicts = {"d1": d1, "d2": d2}
n = len(dicts)
res = {k: sum(d[k] for d in dicts.values()) / n for k in d1}
# {'A': 1.0, 'B': 1.1, 'C': 2.0, 'D': 1.0, 'E': 2.0}
```

Note: This is assuming that, as you wrote in the question, all the dicts have *the same* keys, or are `defaultdicts`

, so that missing keys don't cause an error.

Source (Stackoverflow)

Comments