def merge_dicts(d1, d2, merge):
    """
    Merges two dictionaries, non-destructively, combining
    values on duplicate keys as defined by the final *merge*
    argument.

    This function is a modified version of an answer to a
    `Stack Overflow question <http://stackoverflow.com/questions/38987/>`_
    by rcreswick.
    """
    result = dict(d1)
    for k, v in d2.items():
        result[k] = merge(result[k], v) if k in result else v
    return result
