Python 从包含每个级别键的列表列表中创建任意深度的嵌套字典

Python 从包含每个级别键的列表列表中创建任意深度的嵌套字典,python,python-3.x,list,dictionary,Python,Python 3.x,List,Dictionary,给定的是一个包含任意长度列表的列表。每个列表包含字典的一个级别的键 例如: 给定列表“DL” 最后一级字典(B11、B12)的值应该是空列表。这里有一个简单的递归函数。由于所有嵌套的dict都是相同的,因此该函数只需递归一次以构建子dict,然后使用 dictify(DL)的漂亮打印输出: 这里有一个简单的递归函数。由于所有嵌套的dict都是相同的,因此该函数只需递归一次以构建子dict,然后使用 dictify(DL)的漂亮打印输出: 我的解决方案迭代每个深度,从列表的“末尾”开始,然后迭代每

给定的是一个包含任意长度列表的列表。每个列表包含字典的一个级别的键

例如:

给定列表“DL”


最后一级字典(B11、B12)的值应该是空列表。

这里有一个简单的递归函数。由于所有嵌套的dict都是相同的,因此该函数只需递归一次以构建子dict,然后使用

dictify(DL)
的漂亮打印输出:


这里有一个简单的递归函数。由于所有嵌套的dict都是相同的,因此该函数只需递归一次以构建子dict,然后使用

dictify(DL)
的漂亮打印输出:


我的解决方案迭代每个深度,从列表的“末尾”开始,然后迭代每个元素,将其分配给前一个深度的字典

DL = [['A1'],['A11','A12'],['B1'],['B11','B12']]
DL_rev = DL[::-1] #reverse list - we want to create the smallest dicionaries first

# Initialise dictionary where solution will be stored
my_dictionary = {}

# Calculate depth of dictionaries
depth = len(DL)

# Temporary dictionary
temp = {}

# First initialise the dictionary of empty arrays, into temp
for k in DL_rev[0]:
    temp[k] = []

# For each depth, create a new dictionary
for i in range(1, depth):
    my_dictionary = {}
    # For each element, create an entry for it in the dictionary
    for j in DL_rev[i]:
        my_dictionary[j] = temp.copy()
    temp = my_dictionary.copy() #make a copy of the dictionary, for the next level up

D = {'A1': {'A11': {'B1': {'B11': [], 'B12': []}},
        'A12': {'B1': {'B11': [], 'B12': []}}}}
print(D)
print(my_dictionary)
print(D == my_dictionary)
输出:

{'A1': {'A12': {'B1': {'B12': [], 'B11': []}}, 'A11': {'B1': {'B12': [], 'B11': []}}}}
{'A1': {'A12': {'B1': {'B12': [], 'B11': []}}, 'A11': {'B1': {'B12': [], 'B11': []}}}}
True

我的解决方案迭代每个深度,从列表的“末尾”开始,然后迭代每个元素,将其分配给前一个深度的字典

DL = [['A1'],['A11','A12'],['B1'],['B11','B12']]
DL_rev = DL[::-1] #reverse list - we want to create the smallest dicionaries first

# Initialise dictionary where solution will be stored
my_dictionary = {}

# Calculate depth of dictionaries
depth = len(DL)

# Temporary dictionary
temp = {}

# First initialise the dictionary of empty arrays, into temp
for k in DL_rev[0]:
    temp[k] = []

# For each depth, create a new dictionary
for i in range(1, depth):
    my_dictionary = {}
    # For each element, create an entry for it in the dictionary
    for j in DL_rev[i]:
        my_dictionary[j] = temp.copy()
    temp = my_dictionary.copy() #make a copy of the dictionary, for the next level up

D = {'A1': {'A11': {'B1': {'B11': [], 'B12': []}},
        'A12': {'B1': {'B11': [], 'B12': []}}}}
print(D)
print(my_dictionary)
print(D == my_dictionary)
输出:

{'A1': {'A12': {'B1': {'B12': [], 'B11': []}}, 'A11': {'B1': {'B12': [], 'B11': []}}}}
{'A1': {'A12': {'B1': {'B12': [], 'B11': []}}, 'A11': {'B1': {'B12': [], 'B11': []}}}}
True

该解决方案可以简化为从笛卡尔积创建字典树结构

这是一个基于
collections.defaultdict
itertools.product
的解决方案

from collections import defaultdict
from itertools import product

DL = [['A1'],['A11','A12'],['B1'],['B11','B12']]

rec_dd = lambda: defaultdict(rec_dd)
d = rec_dd()

for route in product(*DL):
    i = d[route[0]]
    for j in route[1:-1]:
        i = i[j]
    i[route[-1]] = []
结果:

defaultdict({'A1': defaultdict({'A11': defaultdict({'B1': defaultdict({'B11': [],
                                                                       'B12': []})}),
                                'A12': defaultdict({'B1': defaultdict({'B11': [],
                                                                       'B12': []})})})})

该解决方案可以简化为从笛卡尔积创建字典树结构

这是一个基于
collections.defaultdict
itertools.product
的解决方案

from collections import defaultdict
from itertools import product

DL = [['A1'],['A11','A12'],['B1'],['B11','B12']]

rec_dd = lambda: defaultdict(rec_dd)
d = rec_dd()

for route in product(*DL):
    i = d[route[0]]
    for j in route[1:-1]:
        i = i[j]
    i[route[-1]] = []
结果:

defaultdict({'A1': defaultdict({'A11': defaultdict({'B1': defaultdict({'B11': [],
                                                                       'B12': []})}),
                                'A12': defaultdict({'B1': defaultdict({'B11': [],
                                                                       'B12': []})})})})

你能给我们看一下输出的是一本真正的字典,而不是ascii艺术的图像吗?到目前为止你做了哪些尝试?请给我一些代码。如果它们是字符串,为什么不把它们变成字符串呢?当我试图回答你的问题时,我要做的第一件事就是插入一堆引号,这样输入就不会引发异常。这不是一个好的开始。你能把输出作为一个实际的字典而不是ascii艺术的图像给我们看吗?到目前为止你做了哪些尝试?请给我一些代码。如果它们是字符串,为什么不把它们变成字符串呢?当我试图回答你的问题时,我要做的第一件事就是插入一堆引号,这样输入就不会引发异常。这不是一个好的开始。您的代码没有正确地复制dicts。其中一些是同一个dict对象;您必须使用
copy.deepcopy(my\u dictionary)
而不是
my\u dictionary.copy()
。(如果您尝试
my_dictionary['A1']['A11']['B1']['B11']=5
,您可以看到这一点-5将在
my_dictionary
中显示两次。)您的代码没有正确复制dicts。其中一些是同一个dict对象;您必须使用
copy.deepcopy(my\u dictionary)
而不是
my\u dictionary.copy()
。(如果您尝试
my_dictionary['A1']['A11']['B1']['B11']=5
,可以看到这一点-5将在
my_dictionary
中显示两次。)