简体   繁体   English

如何基于Python中的匹配键将键值对添加到另一个字典列表中的现有字典列表中

[英]How to append key value pair to an existing list of dict from another list of dict based on matching Key in Python

I am trying to append key value pair to an existing list of dict by comparing the key column. 我试图通过比较键列将键值对附加到现有的字典列表中。

# 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}]

simple approach, no list comps, double loop but works fine: 简单的方法,没有列表组合,双循环但工作正常:

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)

more pythonic, after having defined an helper function to return the union of 2 dictionaries: 在定义了一个辅助函数以返回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+, no need for union aux method, you could write more simply n python 3.5+,不需要工会aux方法,您可以编写得更简单

out = []
for l in lst:
    out.extend({**l,**c} for c in compare_lst if l['NAME']==c['NAME'])

even better: oneliner using itertools.chain to flatten the result of the 2-level list comp 甚至更好:使用itertools.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'] ))

for python 3.5 对于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'] ))

(the multiple methods of doing it materialize the incremental improvements I made those last minutes) (执行此操作的多种方法体现了我在最后几分钟所做的增量改进)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM