如何迭代地创建嵌套字典?

时间:2017-12-28 00:43:02

标签: python dictionary

我想从给定列表创建一个字典,嵌套元素如下所示。例如,给定:

lst = range(1, 11)

如何创建一个函数来从此列表中创建嵌套字典:

dic = {1: {2: {3: {4: {5: {6: {7: {8: {9: 10}}}}}}}}}

4 个答案:

答案 0 :(得分:8)

反转您的列表(或更好的范围对象)。将最后一个(现在第一个)元素作为起始值,并在每次迭代中通过其他反向列表创建一个新的dict:

>>> r = reversed(range(1, 11))
... d = next(r)
... for x in r:
...     d = {x: d}
... d
...
{1: {2: {3: {4: {5: {6: {7: {8: {9: 10}}}}}}}}}

答案 1 :(得分:4)

您可以使用functools.reduce

import functools

lst = range(1, 11)
functools.reduce(lambda x, y: {y: x}, reversed(lst))
# {1: {2: {3: {4: {5: {6: {7: {8: {9: 10}}}}}}}}}

答案 2 :(得分:2)

你可以从里到外构建它:

result = {9: 10}

for i in range(8, 0, -1):
    temp = {i: result}
    result = temp    

print(result)
# outputs {1: {2: {3: {4: {5: {6: {7: {8: {9: 10}}}}}}}}}

答案 3 :(得分:2)

从最里面的价值开始,向外工作。 在每个步骤中,使用上一步骤的dict作为新的val

def nest_dict(lst):
    my_dict = lst[-1]
    for val in lst[-2::-1]:
        my_dict = {val: my_dict}
    return my_dict

print nest_dict(range(1, 11))

输出:

{1: {2: {3: {4: {5: {6: {7: {8: {9: 10}}}}}}}}}