简体   繁体   English

Python:从多个字典中添加值并合并唯一键

[英]Python: Adding values from multiple dictionaries and merging unique keys

I have 2 dictionaries that share about 80% the same keys and the values are 2 element lists. 我有2个字典,它们共享大约80%的相同键,并且值是2个元素列表。 I need to make a new dictionary out of the three that will contain all the keys, including the ones unique to each dictionary and I need the values of the same keys to be summed up. 我需要从三个包含所有键的字典中创建一个新字典,包括每个字典的唯一键,并且我需要对相同键的值求和。

    dict1 = {'Mike': [10,20], 'John': [12,34], 'Steve': [60,10]}
    dict2 = {'Mike': [15,10], 'John': [18,36]}

The new dictionary should look like this : 新字典应如下所示:

    dict3 = {'Mike': [25,30], 'John': [30,70], 'Steve': [60,10]}

Any idea how I should tackle this ? 知道我该如何解决吗?

Take keys from both dicts, iterate through and populate dict3 depending on where that key in both_key belongs to 取钥匙从两个类型的字典,遍历和填充dict3不同的地方在关键both_key属于

both_keys = set(list(dict1.keys()) + list(dict2.keys()))
dict3 = {}
for k in both_keys:
    if k in dict1 and k in dict2:
        dict3[k] = [sum(x) for x in zip(dict1[k], dict2[k])]
    elif k in dict1:
        dict3[k] = dict1[k]
    else:
        dict3[k] = dict2[k]

There are lots of ways to do this, but here is a way that minimizes lookups, which may be helpful if the actual dicts are large: 有很多方法可以做到这一点,但是这是一种最小化查找的方法,如果实际的命令很大,这可能会有所帮助:

keys_1 = set(dict1.keys())
keys_2 = set(dict2.keys())
all_keys = keys_1 | keys_2
for key in all_keys:
    a,b = 0,0
    if key in keys_1:
        a += dict1[key][0]
        b += dict1[key][1]
    if key in keys_2:
        a += dict2[key][0]
        b += dict2[key][1]
    dict3[key] = [a,b]

Here's my attempt at a somewhat functional solution for any number of dicts and any number of values to zip-sum. 这是我为某种数量的字典和任意数量的zip-sum值提供某种功能性解决方案的尝试。

Define how you want to merge entries. 定义您要如何合并条目。 In this case by summing the individual components, materializing the result: 在这种情况下,通过求和各个组成部分,可以实现以下结果:

merge = lambda vs: list(map(sum, zip(*vs)))

Then define how to merge two dicts: 然后定义如何合并两个字典:

def merge_dicts(ds):
    keys = set.union(*map(set, ds))
    return {k: merge(map(lambda d: d.get(k, repeat(0)), ds))
            for k in keys}

Here I just go over the union of all keys, merging every dict's entry, with repeat(0) as default so merge() will just sum up zeroes for missing values. 在这里,我只是遍历所有键的并集,合并了每个字典的条目,默认情况下是repeat(0) ,因此merge()会为缺失值加总为零。

After that you can merge your dicts like this: 之后,您可以像这样合并您的字典:

merged = merge_dicts([dict1, dict2])

my solution use numpy : 我的解决方案使用numpy:

import numpy as np
sum_dict = {}
for key in set(dict1.keys() + dict2.keys()):
    sum_dict[key] = np.add(dict1.get(key, np.zeros(2)), dict2.get(key, np.zeros(2)))
  1. concatenate all the 2 keys 连接所有2个键
  2. loop and using numpy add to sum the values, and the default value is a numpy array of zeros 循环并使用numpy加总和值,并且默认值为零的numpy数组

And convert back to dict of list if you want 并转换回列表字典

dict([(k,list(v)) for (k,v) in sum_dict.items()])
Out[99]:
{'John': [30, 70], 'Mike': [25, 30], 'Steve': [60.0, 10.0]}

Try this: 尝试这个:

dict1 = {'Mike': [10,20], 'John': [12,34], 'Steve': [60,10]}
dict2 = {'Mike': [15,10], 'John': [18,36]}

new_dict = {}

for x, y in dict1.items():
if x in dict2.keys():
    new_dict[x] = [a + b for a, b in zip(dict2[x], dict1[x])]
else:
    new_dict[x] = dict1[x]
print(new_dict)

#Output : {'Mike': [25, 30], 'John': [30, 70], 'Steve': [60, 10]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM