The equivalent of what you're currently doing, but the other way around, is:
unmatched_items_10 = [d for d in entries10 if d not in entries9]
While more concise than your way of coding it, this has the same performance problem: it will take time proportional to the number of items in each list. If the lengths you're interested in are about 9 or 10 (as those numbers seem to indicate), no problem.
But for lists of substantial length you can get much better performance by sorting the lists and "stepping through" them "in parallel" so to speak (time proportional to N log N
where N
is the length of the longer list). There are other possibilities, too (of growing complication;-) if even this more advanced approach is not sufficient to get you the performance you need. I'll refrain from suggesting very complicated stuff unless you indicate that you do require it to get good performance (in which case, please mention the typical lengths of each list and the typical contents of the dicts that are their items, since of course such "details" are the crucial consideration for picking algorithms that are a good compromise between speed and simplicity).
Edit: the OP edited his Q to show what he cares about, for any two dicts d1
and d2
one each from the two lists, is not whether d1 == d2
(which is what the in
operator checks), but rather d1[a]==d2[a] and d1[b]==d2[b]
. In this case the in
operator cannot be used (well, not without some funky wrapping, but that's a complication that's best avoided when feasible;-), but the all
builtin replaces it handily:
unmatched_items_10 = [d for d in entries10
if all(d[a]!=d1[a] or d[b]!=d2[b] for d2 in entries9)]
I have switched the logic around (to !=
and or
, per De Morgan's laws) since we want the dicts that are not matched. However, if you prefer:
unmatched_items_10 = [d for d in entries10
if not any(d[a]==d1[a] and d[b]==d2[b] for d2 in entries9)]
Personally, I don't like if not any
and if not all
, for stylistic reasons, but the maths are impeccable (by what the Wikipedia page calls the Extensions to De Morgan's laws, since any
is an existential quantifier and all
a universal quantifier, so to speak;-). Performance should be just about equivalent (but then, the OP did clarify in a comment that performance is not very important for them on this task).