python dict 合并
迷茫
迷茫 2017-06-14 10:53:21
0
2
910

现有 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上找了个代码改了一下。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板