给定的是包含任意长度列表的列表。每个列表包含字典的一个级别的键。
示例:
列出"DL“
DL = [['A1'],['A11','A12'],['B1'],['B11','B12']] # <- All entries are strings我想要创建一个嵌套字典,它具有以下四个层次的结构:

在Python符号中:
D = {'A1': {'A11': {'B1': {'B11': [], 'B12': []}},
'A12': {'B1': {'B11': [], 'B12': []}}}}上一级字典(B11、B12)的值应该是空列表。
发布于 2018-04-01 13:00:23
这里有一个简单的递归函数。由于所有嵌套的dict都是相同的,因此函数只需递归一次来构建sub,然后使用copy.deepcopy对每个值进行复制。
import copy
def dictify(lst):
if not lst:
return []
sub_dict = dictify(lst[1:])
return {value: copy.deepcopy(sub_dict) for value in lst[0]}印刷精美的dictify(DL)输出
{'A1': {'A11': {'B1': {'B11': [], 'B12': []}},
'A12': {'B1': {'B11': [], 'B12': []}}}}发布于 2018-04-01 13:05:08
我的解决方案遍历每个深度,从列表的“末尾”开始,然后遍历每个元素,将其分配给前一个深度的字典。
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发布于 2018-04-01 13:06:41
解决方案可以简化为从笛卡尔乘积创建字典树结构。
这是一种基于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': []})})})})https://stackoverflow.com/questions/49597963
复制相似问题