我试图通过比较键列将键值对附加到现有的字典列表中。
# 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}]
简单的方法,没有列表组合,双循环但工作正常:
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)
在定义了一个辅助函数以返回2个字典的并集之后,使用了更多的pythonic:
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+,不需要工会aux方法,您可以编写得更简单
out = []
for l in lst:
out.extend({**l,**c} for c in compare_lst if l['NAME']==c['NAME'])
甚至更好:onelineritertools.chain
用于展平2级列表比较的结果
import itertools
out=list(itertools.chain(dict_union(l,c) for l in lst for c in compare_lst if l['NAME']==c['NAME'] ))
对于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'] ))
(执行此操作的多种方法体现了我在最后几分钟所做的渐进式改进)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句