0

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?

undefined
  • 3,464
  • 11
  • 48
  • 90

3 Answers3

1

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}]
Pygirl
  • 12,969
  • 5
  • 30
  • 43
1

Just test if all elements are in the other array

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


def find_diff(array_a, array_b):
    diff = []
    for e in array_a:
        if e not in array_b:
            diff.append(e)
    return diff

print(find_diff(a, b))
print(find_diff(b, a))

the same with list comprehension

def find_diff(array_a, array_b):
    return [e for e in array_a if e not in array_b]
djangoliv
  • 1,698
  • 14
  • 26
1

here is the code for subtracting list of dictionaries

a = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 6, 'f': 6}]
b = [{'a': 1, 'b': 2}, {'g': 3, 'h': 4}, {'f': 6, 'e': 6}]
a_b = []
b_a = []
for element in a:
    if element not in b:
        a_b.append( element )
for element in b:
    if element not in a:
        b_a.append( element )
print("a-b =",a_b)
print("b-a =",b_a)
Shoaib Mirzaei
  • 512
  • 4
  • 11