def build_tree(elems, root, currentkey, parentkey):
    """ Constructs a hierarchic tree from a flat dictionary.

    https://stackoverflow.com/questions/35452512/construct-hierarchy-tree-from-python-flat-parent-children-dict-list

    :param elems: flat dictionary
    :param root: root node of current recursion
    :param currentkey: key of current element
    :param parentkey: key parent element
    """
    elem_with_children = {}

    def _build_children_sub_tree(parent):
        cur_dict = {
          'id': parent,
          # put whatever attributes here
        }
        if parent in elem_with_children.keys():
            cur_dict["children"] = [_build_children_sub_tree(cid) for cid in elem_with_children[parent]]
        return cur_dict

    for item in elems:
        cid = item[currentkey]
        pid = item[parentkey]
        elem_with_children.setdefault(pid, []).append(cid)

    res = _build_children_sub_tree(root)
    return res