您的位置:首页技术文章
文章详情页

python dict 合并

浏览:82日期:2022-06-28 13:55:05

问题描述

现有 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] }]

问题解答

回答1:

l_a = len(a)l_b = len(b)b_map = {}result = []for _ in range(l_b): i = b.pop() b_map[i[’id’]] = ifor _ in range(l_a): i = a.pop() if i[’id’] in b_map:i.update(b_map.pop(i[’id’])) result.append(i)result.extend(b_map.values())print(result)[{’MUT’: ’1500’, ’id’: ’2’}, {’MUT’: ’1500’, ’id’: ’1’, ’neighbor’: [2]}, {’id’: ’3’, ’neighbor’: [2]}]回答2:

from collections import defaultdictdef 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上找了个代码改了一下。

标签: Python 编程
相关文章: