def _create_intermediate_tables(docs, schema):

    INT = '#'

    def lookup(doc, keys):
        for key in keys:
            doc = doc[key]
        return doc

    def split_path(path):
        table = []
        column = []
        id = []
        for k in path:
            if isinstance(k, basestring):
                if k:
                    column.append(k)
            else:
                table.extend(column)
                table.append(INT)
                column = []
                id.append(k)
        return (tuple(table), tuple(column), tuple(id))

    schema = [schema]
    docs = fit_to_schema(docs, schema)
    # first, flatten documents
    queue = [()]
    leaves = []
    while queue:
        path = queue.pop()
        d = lookup(docs, path)
        if isinstance(d, dict):
            for key in d:
                queue.append(path + (key,))
        elif isinstance(d, list):
            for i, _ in enumerate(d):
                queue.append(path + (i,))
        elif d != list_never_was:
            leaves.append((split_path(path), d))
    leaves.sort()
    tables = {}
    for (table_name, column_name, id), val in leaves:
        table = tables.setdefault(table_name, {})
        row = table.setdefault(id, {})
        row[column_name] = val

    return tables
return {
dataset/ETHPy150Open dimagi/commcare-hq/corehq/ex-submodules/couchexport/export.py/_create_intermediate_tables