首頁  >  問答  >  主體

python dict 合併

現有a , b 兩個字典,他們都有一個共同的id 1 , 實現dict的合併
和mysql中select a.id,a.MUT,b.neighbor from a full join b on a.id = b.id
執行結果很類似

    a =  {
        "id": "1",
        "MUT": "1500",
    }
    b =  {
        "id": "1",
        "neighbor": [2]
    }
    # result = addfunction(a,b)
    result = {
        "id": "1",
        "MUT": "1500",
        "neighbor": [2]
    }

如何實現?



考慮複雜情況:

a =  [
    {
        "id": "1",
        "MUT": "1500",
    },
    {
        "id": "2",
        "MUT": "1500",
    }
]
b =  [
    {
        "id": "1",
        "neighbor": [2]
    },
     {
        "id": "3",
        "neighbor": [2]
    }
]
# result = addfunction(a,b)
result = [
    {
        "id": "1",
        "MUT": "1500",
        "neighbor": [2]
    },
     {
        "id": "2",
        "MUT": "1500",
    },
     {
        "id": "3",
        "neighbor": [2]
    }
]
迷茫迷茫2706 天前869

全部回覆(2)我來回復

  • PHP中文网

    PHP中文网2017-06-14 10:55:21

    雷雷

    回覆
    0
  • 某草草

    某草草2017-06-14 10:55:21

    from collections import defaultdict
    
    def combineListDict(l1,l2,joinKeys = ["id"]):
        d = defaultdict(dict)
        for l in (l1, l2):
            for elem in l:
                if len(joinKeys) == 1:
                    joinKeysStr = elem[joinKeys[0]]
                else:
                    joinKeysStr = reduce((lambda x, y: str(elem[x]) + str(elem[y])),joinKeys)
                d[joinKeysStr].update(elem)
        return d.values()
    

    因為join on 條件可能時多個值,我在stack上找了個代碼改了一下。

    回覆
    0
  • 取消回覆