How to merge multiple dicts with same key?

前端 未结 14 2603
别跟我提以往
别跟我提以往 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条回答
  •  感动是毒
    2020-11-22 13:54

    From blubb answer:

    You can also directly form the tuple using values from each list

    ds = [d1, d2]
    d = {}
    for k in d1.keys():
      d[k] = (d1[k], d2[k])
    

    This might be useful if you had a specific ordering for your tuples

    ds = [d1, d2, d3, d4]
    d = {}
    for k in d1.keys():
      d[k] = (d3[k], d1[k], d4[k], d2[k]) #if you wanted tuple in order of d3, d1, d4, d2
    

提交回复
热议问题