[英]How do i create a nested dictionary iteratively?
I want to create a dictionary from a given list, nesting elements as shown below.我想从给定的列表中创建一个字典,嵌套元素如下所示。 For instance, given:例如,给定:
lst = range(1, 11)
how do I create a function to create a nested dictionary from this list:如何创建一个函数来从此列表中创建嵌套字典:
dic = {1: {2: {3: {4: {5: {6: {7: {8: {9: 10}}}}}}}}}
Reverse your list (or better range object).反转您的列表(或更好的范围对象)。 Take the last (now first) element as start value and create a new dict in each iteration through the rest of the reversed list:将最后一个(现在是第一个)元素作为起始值,并通过反向列表的其余部分在每次迭代中创建一个新的字典:
>>> 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}}}}}}}}}
You could use functools.reduce
.您可以使用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}}}}}}}}}
You can build it from inside out:您可以从内到外构建它:
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}}}}}}}}}
Start from the innermost value, working outward.从最内在的价值开始,向外工作。 At each step, use the previous step's dict as the new val
.在每一步,使用上一步的 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))
Output:输出:
{1: {2: {3: {4: {5: {6: {7: {8: {9: 10}}}}}}}}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.