def flip_dict(d):
    """Swap the keys and values in a dictionary, where duplicated values map to a list of keys

    The easiest way to solve this problem is by looping over the keys and values
    of the dictionary using `.items()`. If the value hasn't been seen before, we need
    to set some reasonable default value in our dictionary - in this case, a list to
    store the associated keys. Then, we can append (in-place!) our key to the list
    of keys associated to this value.

    It's possible to write this update step in one line using the default of `.get()`

        out[value] = out.get(value, []).append(key)

    However, I don't think that looks nearly as readable.

    Note: there is a tool in the `collections` module from the standard library
    called `defaultdict` which exports this functionality. You provide it a factory
    method for creating default values in the dictionary (in this case, a list.)
    """
    out = {}
    for key, value in d.items():
        if value not in out:
            out[value] = []
        out[value].append(key)
    return out