面试题答案
一键面试dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'b': 4, 'c': 5, 'd': 6}
result = dict1.copy()
for key, value in dict2.items():
if key in result:
result[key] += value
else:
result[key] = value
print(result)
上述代码中,首先将dict1
复制到result
字典,这样result
就包含了dict1
所有键值对。然后遍历dict2
,如果dict2
中的键在result
中已存在,就将对应的值相加;如果不存在,就将该键值对添加到result
中。最终返回合并后的result
字典。