def merge(x, y, f):
    """ Merges two dictionaries. If a key appears in both dictionaries, the
    common values are merged using the function ``f``"""
    # Start with symmetric difference; keys either in A or B, but not both
    merged = {k: x.get(k, y.get(k)) for k in x.keys() ^ y.keys()}
    # Update with `f()` applied to the intersection
    merged.update(
        {k: f(x[k], y[k]) for k in x.keys() & y.keys()})
    return merged