<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 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 ------- See also: calc_rets() """
  # NOQA
    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