d1 = { 'apples': 2, 'oranges':5 }
d2 = { 'apples': 1, 'bananas': 3 }
result_dict = { 'apples': 1.5, 'oranges': 5, 'bananas': 3 }
What's the best way to do this?
Here is one way:
result = dict(d2)
for k in d1:
if k in result:
result[k] = (result[k] + d1[k]) / 2.0
else:
result[k] = d1[k]
This would work for any number of dictionaries:
dicts = ({"a": 5},{"b": 2, "a": 10}, {"a": 15, "b": 4})
keys = set()
averaged = {}
for d in dicts:
keys.update(d.keys())
for key in keys:
values = [d[key] for d in dicts if key in d]
averaged[key] = float(sum(values)) / len(values)
print averaged
# {'a': 10.0, 'b': 3.0}
Update: @mhyfritz showed a way how you could reduce 3 lines to one!
dicts = ({"a": 5},{"b": 2, "a": 10}, {"a": 15, "b": 4})
averaged = {}
keys = set().union(*dicts)
for key in keys:
values = [d[key] for d in dicts if key in d]
averaged[key] = float(sum(values)) / len(values)
print averaged
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With