def deep_merge(a, b):
    """ Merge two dictionaries recursively. """
    def merge_values(k, v1, v2):
        if isinstance(v1, dict) and isinstance(v2, dict):
            return k, deep_merge(v1, v2)
        else:
            return k, v2
    a_keys = set(a.keys())
    b_keys = set(b.keys())
    pairs = [merge_values(k, a[k], b[k]) for k in a_keys & b_keys] \
            + [(k, a[k]) for k in a_keys - b_keys] \
            + [(k, b[k]) for k in b_keys - a_keys]
    return dict(pairs)