def dedup(d, preferred):
    """
    Remove duplicate entries from a dict.

    Keys in preferred will be included in the resulting dict if possible.
    (Later keys are favored over earlier ones.)

    """
    rev = {v: k for k, v in d.items()}
    for key in preferred:
        rev[d[key]] = key
    return {k: v for v, k in rev.items()}