我试图通过比较键列来将键值对附加到现有的dict列表中。
# Initial list of dict
lst = [{'NAME': 'TEST', 'TYPE': 'TEMP'},
{'NAME': 'TEST', 'TYPE': 'PERMANENT'},
{'NAME': 'TEST1', 'TYPE': 'TEMP'}]
# From the below list of dict, the Key (NAME only) need to compare with the initial list dict
# and for any match need to append the rest of key value pair to the initial list of dict.
compare_lst = [{'NAME': 'TEST', 'ID': 70001, 'V_KEY': 67, 'R_KEY': 1042, 'W_ID': 22},
{'NAME': 'TEST1','ID': 70005, 'V_KEY': 75, 'R_KEY': 1047, 'W_ID': 28}]
# Expected Out put
out = [{'NAME': 'TEST', 'TYPE': 'TEMP', 'ID': 70001, 'V_KEY': 67, 'R_KEY': 1042, 'W_ID': 22},
{'NAME': 'TEST', 'TYPE': 'PERMANENT', 'ID': 70001, 'V_KEY': 67, 'R_KEY': 1042, 'W_ID': 22},
{'NAME': 'TEST1', 'TYPE': 'TEMP', 'ID': 70005, 'V_KEY': 75, 'R_KEY': 1047, 'W_ID': 28}]
答案 0 :(得分:1)
简单的方法,没有列表comps,双循环但工作正常:
out=[]
for l in lst:
for c in compare_lst:
if l['NAME']==c['NAME']: # same "key": merge
lc = dict(l)
lc.update(c) # lc is the union of both dictionaries
out.append(lc)
print(out)
更多pythonic,在定义了一个帮助函数以返回2个字典的并集后:
out=[]
def dict_union(a,b):
r = dict(a)
r.update(b)
return r
for l in lst:
out.extend(dict_union(l,c) for c in compare_lst if l['NAME']==c['NAME'])
n python 3.5+,不需要union aux方法,你可以写得更简单
out = []
for l in lst:
out.extend({**l,**c} for c in compare_lst if l['NAME']==c['NAME'])
更好:oneliner使用itertools.chain
来压缩2级列表comp的结果
import itertools
out=list(itertools.chain(dict_union(l,c) for l in lst for c in compare_lst if l['NAME']==c['NAME'] ))
for python 3.5
import itertools
out=list(itertools.chain({**l,**c} for l in lst for c in compare_lst if l['NAME']==c['NAME'] ))
(这样做的多种方法实现了我最后几分钟所做的增量改进)