def nest(dict_in, delim="__"):
    """Nests the input dict by splitting keys (opposite of flatten above)"""
    # We will loop through all keys first, and keep track of any first-level keys
    # that will require a recursive nest call. 'renest' stores these keys
    output, renest = {}, []
    for key in dict_in:
        if delim not in key:
            output[key] = dict_in[key]
            continue
        loc = key.split(delim, 1)
        if loc[0] not in output:
            output[loc[0]] = {}
            # Uniquely add the key to the subdictionary we want to renest
            renest.append(loc[0])
        output[loc[0]][loc[1]] = dict_in[key]

    # Renest all higher-level dictionaries
    for renest_key in renest:
        output[renest_key] = nest(output[renest_key])
    return output