How to merge multiple dicts with same key?

前端 未结 14 2540
别跟我提以往
别跟我提以往 2020-11-22 13:12

I have multiple dicts/key-value pairs like this:

d1 = {key1: x1, key2: y1}  
d2 = {key1: x2, key2: y2}  

I want the result to be a new di

14条回答
  •  Happy的楠姐
    2020-11-22 13:50

    dict1 = {'m': 2, 'n': 4}
    dict2 = {'n': 3, 'm': 1}
    

    Making sure that the keys are in the same order:

    dict2_sorted = {i:dict2[i] for i in dict1.keys()}
    
    keys = dict1.keys()
    values = zip(dict1.values(), dict2_sorted.values())
    dictionary = dict(zip(keys, values))
    

    gives:

    {'m': (2, 1), 'n': (4, 3)}
    

提交回复
热议问题