2016-11-03 9 views
0

キー列を比較することによって、既存のdictのリストにキー値のペアを追加しようとしています。キーの値のペアを既存のdictのリストに追加するにはどうすればいいですか?PythonのKeyと一致するキーに基づいて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}] 

答えて

1

単純なアプローチ、リストなしカンプ、ダブルループが、正常に動作します:

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つの辞書の労働組合を返すためにヘルパー関数を定義した後:

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

さらに良い:パイソン3.5

import itertools  
out=list(itertools.chain({**l,**c} for l in lst for c in compare_lst if l['NAME']==c['NAME'])) 

(それは私が作った漸進的な改善を実体行うための複数の方法のための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'])) 

の結果を平らにするitertools.chainを使用してonelinerそれらの最後の分)

+0

ありがとう..それは働いた..私はPython 3.5のワードで見ている.. – Pradeep

関連する問題