1

I'am trying to compare 2 lists of dictionary to replace equal values. 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'

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])
1
  • What should your output be? You can just get the common keys, and do the comparision only on them. Commented Jul 11, 2017 at 19:14

1 Answer 1

2

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'}]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.