0

How should I subtract two list of dictionaries in a pythonic way?

I want to find the element that are unique in the first listOfDict.

See my example below:

firstDict = [{'A':1 ,'B':1}, {'A':2 ,'B':2}]
secondDict = [{'A':3 ,'B':3}, {'A':2 ,'B':2}]

magicFunction(A, B) should return

[{'A':1 ,'B':1}

and magicFunction(B, A) should return

[{'A':3 ,'B':3}
Cœur
  • 37,241
  • 25
  • 195
  • 267
theAlse
  • 5,577
  • 11
  • 68
  • 110

1 Answers1

1

You could use sets for that, but a dict can not be added to a set unfortunately. You need to 'cast' the dictionaries to something that a set can handle, e.g. a immutable type such as a sequence of tuples. Combine that with an index to return the referenced dict:

def magicFunction(a, b):
    a = [tuple(sorted(d.items())) for d in a]
    b = [tuple(sorted(d.items())) for d in b]
    return [dict(kvs) for kvs in set(a).difference(b)]

Result:

>>> firstDict = [{'A':1 ,'B':1}, {'A':2 ,'B':2}]
>>> secondDict = [{'A':3 ,'B':3}, {'A':2 ,'B':2}]
>>> magicFunction(firstDict, secondDict)
[{'A': 1, 'B': 1}]
>>> magicFunction(secondDict, firstDict)
[{'A': 3, 'B': 3}]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343