def fold(data, prefix='', delimeter='__'):
    """
    >>> _dd(fold({'a__a': 4}))
    "{'a': {'a': 4}}"
    >>> _dd(fold({'a__a': 4, 'a__b': 5}))
    "{'a': {'a': 4, 'b': 5}}"
    >>> _dd(fold({'a__1': 2, 'a__0': 1, 'a__2': 3}))
    "{'a': [1, 2, 3]}"
    >>> _dd(fold({'form__a__b': 5, 'form__a__a': 4}, 'form'))
    "{'a': {'a': 4, 'b': 5}}"
    >>> _dd(fold({'form__a__b': 5, 'form__a__a__0': 4, 'form__a__a__1': 7}, 'form'))
    "{'a': {'a': [4, 7], 'b': 5}}"
    >>> repr(fold({'form__1__b': 5, 'form__0__a__0': 4, 'form__0__a__1': 7}, 'form'))
    "[{'a': [4, 7]}, {'b': 5}]"
    """
    if not isinstance(delimeter, (tuple, list)):
        delimeter = (delimeter, )

    def deep(data):
        if len(data) == 1 and len(data[0][0]) < 2:
            if data[0][0]:
                return {data[0][0][0]: data[0][1]}
            return data[0][1]

        collect = {}
        for key, group in groupby(data, lambda kv: kv[0][0]):
            nest_data = [(k[1:], v) for k, v in group]
            collect[key] = deep(nest_data)

        is_num = all(k.isdigit() for k in collect.keys())
        if is_num:
            return [i[1] for i in sorted(collect.items())]
        return collect

    data_ = [
        (split(key, delimeter), value)
        for key, value in sorted(data.items())
    ]
    result = deep(data_)
    return result[prefix] if prefix else result
def fold ( data , prefix = '' , delimeter = '__' ) : if not isinstance ( delimeter , ( tuple , list ) ) : delimeter = ( delimeter , ) def deep ( data ) : if len ( data ) == 1 and len ( data [ 0 ] [ 0 ] ) < 2 : if data [ 0 ] [ 0 ] : return { data [ 0 ] [ 0 ] [ 0 ] : data [ 0 ] [ 1 ] } return data [ 0 ] [ 1 ] collect = { } for key , group in groupby ( data , lambda kv : kv [ 0 ] [ 0 ] ) : nest_data = [ ( k [ 1 : ] , v ) for k , v in group ] collect [ key ] = deep ( nest_data ) is_num = all ( k . isdigit ( ) for k in collect . keys ( ) ) if is_num : return [ i [ 1 ] for i in sorted ( collect . items ( ) ) ] return collect data_ = [ ( split ( key , delimeter ) , value ) for key , value in sorted ( data . items ( ) ) ] result = deep ( data_ ) return result [ prefix ] if prefix else result
>>> _dd(fold({'a__a': 4}))
    "{'a': {'a': 4}}"
    >>> _dd(fold({'a__a': 4, 'a__b': 5}))
    "{'a': {'a': 4, 'b': 5}}"
    >>> _dd(fold({'a__1': 2, 'a__0': 1, 'a__2': 3}))
    "{'a': [1, 2, 3]}"
    >>> _dd(fold({'form__a__b': 5, 'form__a__a': 4}, 'form'))
    "{'a': {'a': 4, 'b': 5}}"
    >>> _dd(fold({'form__a__b': 5, 'form__a__a__0': 4, 'form__a__a__1': 7}, 'form'))
    "{'a': {'a': [4, 7], 'b': 5}}"
    >>> repr(fold({'form__1__b': 5, 'form__0__a__0': 4, 'form__0__a__1': 7}, 'form'))
    "[{'a': [4, 7]}, {'b': 5}]"