pythonarraysobjectpydash

find difference of values between 2 array of objects in python


I have 2 array of objects:

a = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}]
b = [{'a': 1, 'b': 2}, {'g': 3, 'h': 4}, {'f': 6, 'e': 5}]

Output:
a - b = [{'c': 3, 'd': 4}] ("-" symbol is only for representation, showing difference. Not mathematical minus.)
b - a = [{'g': 3, 'h': 4}]

In every array, the order of key may be different. I can try following and check for that:

for i in range(len(a)):
   current_val = a[i]
   for x, y in current_val.items:
      //search x keyword in array b and compare it with b

but this approach doesn't feel right. Is there simpler way to do this or any utility library which can do this similar to fnc or pydash?


Solution

  • You can use lambda:

    g = lambda a,b : [x for x in a if x not in b]
    

    g(a,b) # a-b
    

    [{'c': 3, 'd': 4}]
    


    g(b,a) # b-a
    

    [{'g': 3, 'h': 4}]