如何将2个字典合并到python中的新字典中

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



评论
nin
nin

You may use a defaultdict and a list as type of value, then iterate both dict1 and dict2 and their value in the list pointed by the key

def mergeDicts(dict1, dict2):
    dict3 = defaultdict(list)
    for key, value in dict1.items():
        dict3[key].append(value)
    for key, value in dict2.items():
        dict3[key].append(value)
    return dict(dict3)
点赞
评论
被窝﹖爱
被窝﹖爱

我相信这比其他答案更接近您想要的。

def mergeDicts(dict1, dict2):
    dict3 = {}
    for key, value in dict1.items():
        if key in dict2:
            dict3[key] = (value, dict2[key])
return dict3
点赞
评论