[英]compare different keys in two lists of dictionary in python
我正在嘗試比較2個字典列表以替換相等的值。 例如:
d1 = [{'a': 'hello', 'b':'world','c':'this','d':'is'},{'a':'ddd' ,'b': 'www','c':'hah','d':'tt'},.....]
d2 = [{'Q': 'hello', 'H':'target_word','K':'that','N':'was'},{'Q':'world' ,'H': 'target_word','K':'hah','N':'txt'},.....]
有人可以告訴我如何將d1中的鍵(“ a”,“ b”)與d2中的“ Q”進行比較(如果它們具有相同的值),則必須將d1中的“ a”和“ b”值替換為“ H”中的值d2是“ target_word”
這是我的嘗試之一:
for i in d1:
for j in d2:
for k in i.keys():
for k1 in j.keys():
if j[k1] == i[k]:
i[k] = j ['H']
list.append(i[k])
看起來如何?
d1 = [{'a': 'hello', 'b':'world','c':'this','d':'is'},{'a':'ddd' ,'b': 'www','c':'hah','d':'tt'}]
d2 = [{'Q': 'hello', 'H':'target_word','K':'that','N':'was'},{'Q':'world' ,'H': 'target_word','K':'hah','N':'txt'}]
for input in d1:
for queries in d2:
for val in ("a", "b"):
if input[val] == queries["Q"]:
input[val] = queries["H"]
輸出:
>>> d1
[{'a': 'target_word', 'c': 'this', 'b': 'target_word', 'd': 'is'}, {'a': 'ddd', 'c': 'hah', 'b': 'www', 'd': 'tt'}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.