Hypothetical Ninja
Hypothetical Ninja

Reputation: 4077

Combine Dictionaries With average values for similar keys,Python

I have 2 dictionaries that I need to combine.

dict_a = {'key1':[40,70],'key2':[35,76],'key4':[45,90]}  
dict_b = {'key1':[38,72],'key3':[37,89.56],'key4':[47,88]}

And I want a third dictionary such that it combines both and assigns average values for identical keys.

dict_c ={'key1':[39,71],'key2':[35,76],'key3':[37,89.56],'key4':[46,89]}

Please Note the following:

1.Each key has a list value with 2 elements.
2.The values in list can be int or float.
3.The value for Identical keys gets average like-- key1:[39,71] and so on

Upvotes: 2

Views: 1233

Answers (2)

Kobi K
Kobi K

Reputation: 7931

Code:

dict_a = {'key1':[40,70],'key2':[35,76],'key4':[45,90]}
dict_b = {'key1':[38,72],'key3':[37,89.56],'key4':[47,88]}

dict_c = {}
for key1, vals1 in dict_a.iteritems():
    try:
        vals2 = dict_b[key1]
        dict_c[key1] = [sum([val1, val2]) / 2 for val1, val2 in zip(vals1, vals2)]
    except KeyError:
        dict_c.update({key1: dict_a[key1]})

for key in dict_b:
    if key not in dict_c:
        dict_c.update({key: dict_b[key]})

print dict_c

Output:

{'key3': [37, 89.56], 'key2': [35, 76], 'key1': [39, 71], 'key4': [46, 89]}

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

d = {}
for k, v in dict_a.items():
    if k in dict_b:
        val1, val2 =  (v[0]+ dict_b[k][0]) / 2, (v[1] + dict_b[k][1]) / 2 # average sum of ele1 and ele2 in each value list
        d[k] = [val1, val2] # set new value to key
    else:
        d[k] = v # else just add the k,v 

for k,v in dict_b.items(): # add rest of keys from dict_b
    if k not in d: # if key not already in d add it
        d[k] = v
print d

{'key3': [37, 89.56], 'key2': [35, 76], 'key1': [39, 71], 'key4': [46, 89]}

If you don't want to use dict_b again:

d = {}
for k, v in dict_a.items():
    if k in dict_b:
        val1, val2 = (v[0]+ dict_b[k][0]) / 2, (v[1] + dict_b[k][1]) / 2 # average sum of ele1 and ele2 in each value list
        d[k] = [val1, val2] # set new value to key
        del dict_b[k] # remove key
    else:
        d[k] = v # else just add the k,v

d.update(dict_b) # update with remainder of dict_b

Upvotes: 1

Related Questions