2017-08-16 52 views

回答

1

这是一个班轮,将做到这一点:

dict1 = {'a': 5, 'b': 7} 
dict2 = {'a': 3, 'c': 1} 

result = {key: dict1.get(key, 0) + dict2.get(key, 0) 
      for key in set(dict1) | set(dict2)} 
# {'c': 1, 'b': 7, 'a': 8} 

注意set(dict1) | set(dict2)是集两者的字典的键。如果密钥存在,则dict1.get(key, 0)返回dict1[key],否则0

0

这里是你一个很好的功能:

def merge_dictionaries(dict1, dict2): 
    merged_dictionary = {} 

    for key in dict1: 
     if key in dict2: 
      new_value = dict1[key] + dict2[key] 
     else: 
      new_value = dict1[key] 

     merged_dictionary[key] = new_value 

    for key in dict2: 
     if key not in merged_dictionary: 
      merged_dictionary[key] = dict2[key] 

    return merged_dictionary 

通过写

dict1 = {'a': 5, 'b': 7} 
dict2 = {'a': 3, 'c': 1} 
result = merge_dictionaries(dict1, dict2) 

结果将是:

{'a': 8, 'b': 7, 'c': 1} 
0

您可以使用collections.Counter它实现此外+这样:

>>> from collections import Counter 
>>> dict1 = Counter({'a': 5, 'b': 7}) 
>>> dict2 = Counter({'a': 3, 'c': 1}) 
>>> dict1 + dict2 
Counter({'a': 8, 'b': 7, 'c': 1}) 

,如果你真的想要的结果作为字典,你可以将它转换回算账:

>>> dict(dict1 + dict2) 
{'a': 8, 'b': 7, 'c': 1}