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, so that it combines both and assigns mean 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 two items.
2. The values ​​in the list can be int or float .
3. The value for Identical keys gets the average value as: key1: [39,71], etc.

+1
source share
2 answers
 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 do not 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 
+1
source

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]} 
0
source

Source: https://habr.com/ru/post/974106/


All Articles