pythondictionaryset-intersectiondisjoint-sets

Check if two dictionaries are disjoint


Is there an easier/faster way to find out if two dictionaries are disjoint than calculating their intersection?

For the intersection I found this answer, so the disjoint-test would look like this:

def dicts_disjoint(a, b):
    keys_a = set(a.keys())
    keys_b = set(b.keys())
    intersection = keys_a & keys_b
    return not len(intersection)

However I think this is inefficient since it always calculates the whole intersection (no short-circuit quit).

Any better ideas?


Solution

  • Are you looking for something like:

    def dicts_disjoint(a, b):
        return not any(k in b for k in a)
    

    Or:

    def dicts_disjoint(a, b):
        return all(k not in b for k in a)
    

    Both will short-circuit.