Reputation: 1189
Say we have 2 lists of dictionaries L1 and L2.
I want to have a list of dictionaries that are in L2 but not in L1. In my case, I have L1 is a subset of L2 so im not sure if that fact can be used to make any optimizations.
Upvotes: 0
Views: 732
Reputation: 106946
You can use list comprehension:
L1 = [{1: 2, 2: 3}, {2: 3, 3: 4}]
L2 = [{1: 2, 2: 3}, {4: 5, 5: 6}]
print([d for d in L2 if d not in L1])
This outputs:
[{4: 5, 5: 6}]
Or if you have a large list of dicts, you should convert L1
to a set of tuples for efficient membership lookup:
set1 = set(tuple(d.items()) for d in L1)
print([d for d in L2 if tuple(d.items()) not in set1])
Upvotes: 4
Reputation: 2831
solution
[_dict for _dict in l1 if _dict not in l2]
This will get the dictionaries which are in l1 but not in l2
Upvotes: 2