def unflatten(flat_weights):
    """
    Pivot weights from long DataFrame into weighting matrix.

    Parameters
    ----------
    flat_weights: pandas.DataFrame
        A long DataFrame of weights, where columns are "date", "contract",
        "generic", "weight" and optionally "key". If "key" column is
        present a dictionary of unflattened DataFrames is returned with the
        dictionary keys corresponding to the "key" column and each sub
        DataFrame containing rows for this key.

    Returns
    -------
    A DataFrame or dict of DataFrames of instrument weights with a MultiIndex
    where the top level contains pandas.Timestamps and the second level is
    instrument names. The columns consist of generic names. If dict is returned
    the dict keys correspond to the "key" column of the input.

    Example
    -------
    >>> import pandas as pd
    >>> from pandas import Timestamp as TS
    >>> import mapping.util as util
    >>> long_wts = pd.DataFrame(
    ...         {"date": [TS('2015-01-03')] * 4 + [TS('2015-01-04')] * 4,
    ...          "contract": ['CLF5'] * 2 + ['CLG5'] * 4 + ['CLH5'] * 2,
    ...          "generic": ["CL1", "CL2"] * 4,
    ...          "weight": [1, 0, 0, 1, 1, 0, 0, 1]}
    ...     ).loc[:, ["date", "contract", "generic", "weight"]]
    >>> util.unflatten(long_wts)

    See also: calc_rets()
    """
    if flat_weights.columns.contains('key'):
        weights = {}
        for key in flat_weights.loc[:, ('key')].unique():
            flt_wts = flat_weights.loc[(flat_weights.loc[:, ('key')] == key), :
                ]
            flt_wts = flt_wts.drop(labels='key', axis=1)
            wts = flt_wts.pivot_table(index=['date', 'contract'], columns=[
                'generic'], values=['weight'])
            wts.columns = wts.columns.droplevel(0)
            weights[key] = wts
    else:
        weights = flat_weights.pivot_table(index=['date', 'contract'],
            columns=['generic'], values=['weight'])
        weights.columns = weights.columns.droplevel(0)
    return weights
