dict1 = {a: 5, b: 7}
dict2 = {a: 3, c: 1}
result {a:8, b:7, c:1}
如何获得结果?
答案 0 :(得分:9)
这是一个可以做到这一点的单线:
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
。
答案 1 :(得分:7)
您可以使用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,你可以在之后把它丢回:
>>> dict(dict1 + dict2)
{'a': 8, 'b': 7, 'c': 1}
答案 2 :(得分: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}
答案 3 :(得分:0)
一种快速的字典理解方法,适用于接受+运算符的任何类。性能可能不是最佳的。
{
**dict1,
**{ k:(dict1[k]+v if k in dict1 else v)
for k,v in dict2.items() }
}
答案 4 :(得分:0)
Here is another approach but it is quite lengthy!
d1 = {'a': 5, 'b': 7}
d2 = {'a': 3, 'c': 1}
d={}
for i,j in d1.items():
for k,l in d2.items():
if i==k:
c={i:j+l}
d.update(c)
for i,j in d1.items():
if i not in d:
d.update({i:j})
for m,n in d2.items():
if m not in d:
d.update({m:n})
答案 5 :(得分:0)
def merge_dicts(*dict_args):
"""
Given any number of dictionaries, shallow copy and merge into a new dict, precedence goes to key-value pairs in latter dictionaries.
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result
x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}
z = merge_dicts(x, y)
print(z)
{'a': 1, 'b': 10, 'c': 11}
[Program finished]