How to compare dictionaries inside lists

I was wondering if you can help me.

I have two lists that contain dictionaries, for the most part these keys are the same. The following is a brief example:

x1 = [{'a':1,'b':"cat"},{'a':2,'b':"parrot"},...]
x2 = [{'a':2,'b':"dog"},{'a':1,'b':"fish"},...]

Now I would like to compare values ​​based on the key, that is, the key a, but the length of both lists will not always be the same. The key a will always be in both dictionaries, if there is a corresponding dictionary ie x1[0]['a'] == x2[1]['a'].

How can I compare these dictionaries based on the key a, so that I can first discard those x1that do not appear in x2, vice versa. Then determine if certain values ​​appear in both dictionaries and then write them to the database, this is not necessary here.

What I thought was to combine these dictionaries into a tuple in a list based on a key. Then repeat this and compare these values. This is probably not the best way to do this, so if you have any better ideas, please feel free to. :)

[Edit].

I did not clearly formulate this question, sorry. What I hope to do; first: match dictionaries based on key a. Second: ignore those that do not match (key a). Third: compare key b. fourth: update the database based on the comparison b.

Thanks to all who responded.

My answer would be something like this:

"I thought a comp list could do well to build a tuple containing a dictionary from x1, which matches a dictionary from x2, and then iterate over each element of comparison b, but I thought it might be too slow."

, . :)

.

+4
4

, , - , , "a" . , "a" "a" "b".

x1 = [{'a':1,'b':"cat"}, {'a':2,'b':"parrot"}, {'a': 3, 'b': 'dog'}]
x2 = [{'a':2,'b':"dog"}, {'a':1,'b':"fish"}]
x1_d = {d['a']: d['b'] for d in x1}
x2_d = {d['a']: d['b'] for d in x2}
matched_keys = set(x1_d) & set(x2_d)
result = {key: (x1_d[key], x2_d[key]) for key in matched_keys}
print result     # {1: ('cat', 'fish'), 2: ('parrot', 'dog')}

, , , , , .

+1

, ,

len(x1)==len(x2) and all(a['a']==b['a'] for (a, b) in zip(x1, x2))

, ( ),

[a['a'] for a in x1] == [b['a'] for b in x2]
+2

[ a['a'] == b['a'] for a, b in zip(x1, x2) ]

. , , .

Note that the result will be a list of boolean values ​​( True, False). If you want anything else, please indicate this more clearly.

+1
source
x1 = [{'a':1,'b':"cat"},{'a':2,'b':"parrot"}]
x2 = [{'a':2,'b':"dog"},{'a':1,'b':"fish"},{'a':3},{'a':2}]

[(_x2,_x2['a'] in [_x1['a'] for _x1 in x1]) for _x2 in x2]
[({'a': 2, 'b': 'dog'}, True),
 ({'a': 1, 'b': 'fish'}, True),
 ({'a': 3}, False),
 ({'a': 2}, True)]

This code works in one direction. You can adapt it in both directions or just use it twice.

+1
source

All Articles