python dict 合併
迷茫
迷茫 2017-06-14 10:53:21
0
2
894

現有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]
    }
]
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回覆(2)
Ty80

雷雷

某草草
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上找了個代碼改了一下。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板