搜索

首页  >  问答  >  正文

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]
    }
]
迷茫迷茫2723 天前895

全部回复(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
  • 取消回复