简体   繁体   English

比较python中字典的两个列表中的不同键

[英]compare different keys in two lists of dictionary in python

I'am trying to compare 2 lists of dictionary to replace equal values. 我正在尝试比较2个字典列表以替换相等的值。 for example: 例如:

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'},.....]

Can someone tell me how can I compare the keys ('a','b') in d1 with 'Q' in d2 if they have the same value then it must replace 'a's and 'b's value in d1 to 'H's value in d2 which is 'target_word' 有人可以告诉我如何将d1中的键(“ a”,“ b”)与d2中的“ Q”进行比较(如果它们具有相同的值),则必须将d1中的“ a”和“ b”值替换为“ H”中的值d2是“ target_word”

this one of my attempts: 这是我的尝试之一:

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

How does this look? 看起来如何?

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"]

Output: 输出:

>>> 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.

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