def flatten(weights):
    if isinstance(weights, pd.DataFrame):
        wts = weights.stack().reset_index()
        wts.columns = ["date", "contract", "generic", "weight"]
    elif isinstance(weights, dict):
        wts = []
        for key in sorted(weights.keys()):
            wt = weights[key].stack().reset_index()
            wt.columns = ["date", "contract", "generic", "weight"]
            wt.loc[:, "key"] = key
            wts.append(wt)
        wts = pd.concat(wts, axis=0).reset_index(drop=True)
    else:
        raise ValueError("weights must be pd.DataFrame or dict")
    return wts