我需要合并2个词典。
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 ={'key1':[39,71],'key2':[35,76],'key3':[37,89.56],'key4':[46,89]}
请注意以下事项:
1.每个键都有一个包含2个元素的列表值 2.列表中的值可以是 int 或 float 3. 相同密钥的值变为平均值,如 - key1:[39,71],等等
答案 0 :(得分:1)
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]}
如果您不想再次使用dict_b
:
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 :(得分:0)
代码:
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
输出:
{'key3': [37, 89.56], 'key2': [35, 76], 'key1': [39, 71], 'key4': [46, 89]}