从 python 中的列表构建嵌套字典

building nested dictionary from list in python

接下来我有一个项目列表,我想创建它们的树视图我想将它转换为 python 中的父子格式,我尝试了很多。我已经为这个问题坚持了一整天的解决方案。谁能帮帮我

a = [
        ['management', 'users', 'view'],
        ['management', 'group', 'add'],
        ['management', 'users', 'delete']
    ]

试试这个:

a = [
        ['management', 'users', 'view'],
        ['management', 'group', 'add'],
        ['management', 'users', 'delete']
    ]

print(generate_tree_based_data_structure(a))


def generate_tree_based_data_structure(data):
    """Function that creates a tree-based data structure from a list o lists."""

    list_of_dicts = [list_to_dict(d) for d in data]
    general_dict  = {}
    for dict_ in list_of_dicts:
        general_dict = join_two_dicts(general_dict, dict_)
    return general_dict


def join_two_dicts(general_dict, new_dict):
    """Recursive function that merges two dictionaries in a nested one."""

    if isinstance(general_dict, dict) and isinstance(new_dict, dict):
        if set(new_dict).issubset(set(general_dict)):
            key = list(new_dict)[0]
            new_dict = {key: join_two_dicts(general_dict[key], new_dict[key])}
        return {**general_dict, **new_dict}
    elif isinstance(general_dict, dict) or isinstance(new_dict, dict):
        raise Exception('There is some leaf node missing!')
    else:
        return list(set(general_dict + new_dict))


def list_to_dict(list_):
    """Recursive function to generate a (nested) dictionary from a list."""

    if len(list_) == 0:
        dict_ = {}
    elif len(list_) == 1:
        dict_ = {list_[0]: []}
    elif len(list_) == 2:
        dict_ = {list_[0]: [list_[1]]}
    else:
        dict_ = {list_[0]: list_to_dict(list_[1:])}
    return dict_

你可以用其他数据试试看是否有效。