簡體   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

我試圖通過比較鍵列將鍵值對附加到現有的字典列表中。

# 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'])

甚至更好:使用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'] ))

對於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'] ))

(執行此操作的多種方法體現了我在最后幾分鍾所做的增量改進)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM