dict1 = {1:3,2:4} dict2 = {1:5,2:6} 这些必须返回 dict3 = {1:(3,5),2:(4,6)} 如何创建像我一样的dict3我也想先获得第一个值而不是像{1:(5,3)} 我尝试了这个,但是从字面上看却没有
def mergeDicts(dict1, dict2):
dict3 = {**dict1, **dict2}
for key, value in dict3.items():
if key in dict1 and key in dict2:
dict3[key] = (value , dict1[key])
return dict3
You may use a
defaultdict
and alist
as type of value, then iterate bothdict1
anddict2
and their value in the list pointed by the key我相信这比其他答案更接近您想要的。