首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从包含每个级别键的列表中创建任意深度的嵌套字典

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

Stack Overflow用户
提问于 2018-04-01 12:17:25
回答 3查看 1.4K关注 0票数 0

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

示例:

列出"DL“

代码语言:javascript
复制
DL = [['A1'],['A11','A12'],['B1'],['B11','B12']] # <- All entries are strings

我想要创建一个嵌套字典,它具有以下四个层次的结构:

在Python符号中:

代码语言:javascript
复制
D = {'A1': {'A11': {'B1': {'B11': [], 'B12': []}},
            'A12': {'B1': {'B11': [], 'B12': []}}}}

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-04-01 13:00:23

这里有一个简单的递归函数。由于所有嵌套的dict都是相同的,因此函数只需递归一次来构建sub,然后使用copy.deepcopy对每个值进行复制。

代码语言:javascript
复制
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)输出

代码语言:javascript
复制
{'A1': {'A11': {'B1': {'B11': [], 'B12': []}},
        'A12': {'B1': {'B11': [], 'B12': []}}}}
票数 3
EN

Stack Overflow用户

发布于 2018-04-01 13:05:08

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

代码语言:javascript
复制
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)

输出:

代码语言:javascript
复制
{'A1': {'A12': {'B1': {'B12': [], 'B11': []}}, 'A11': {'B1': {'B12': [], 'B11': []}}}}
{'A1': {'A12': {'B1': {'B12': [], 'B11': []}}, 'A11': {'B1': {'B12': [], 'B11': []}}}}
True
票数 0
EN

Stack Overflow用户

发布于 2018-04-01 13:06:41

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

这是一种基于collections.defaultdictitertools.product的解决方案。

代码语言:javascript
复制
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]] = []

结果:

代码语言:javascript
复制
defaultdict({'A1': defaultdict({'A11': defaultdict({'B1': defaultdict({'B11': [],
                                                                       'B12': []})}),
                                'A12': defaultdict({'B1': defaultdict({'B11': [],
                                                                       'B12': []})})})})
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49597963

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档