Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most pythonic way to merge 2 dictionaries, but make the values the average values?

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?

like image 403
TIMEX Avatar asked Jul 13 '11 10:07

TIMEX


2 Answers

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]
like image 120
Eli Bendersky Avatar answered Nov 15 '22 02:11

Eli Bendersky


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
like image 38
phant0m Avatar answered Nov 15 '22 03:11

phant0m