动态嵌套python字典
我想创建一个函数,在python字典中创建动态嵌套级别。 e、 g.如果调用我的函数嵌套,我希望得到如下输出:动态嵌套python字典,python,dictionary,Python,Dictionary,我想创建一个函数,在python字典中创建动态嵌套级别。 e、 g.如果调用我的函数嵌套,我希望得到如下输出: nesting(1) : dict = {key1:<value>} nesting(2) : dict = {key1:{key2:<value>}} nesting(3) : dict = {key1:{key2:{key3:<value>}}} 该模式是针对这种情况动态构建的。您可以像这样迭代键: def nesting(leve
nesting(1) : dict = {key1:<value>}
nesting(2) : dict = {key1:{key2:<value>}}
nesting(3) : dict = {key1:{key2:{key3:<value>}}}
该模式是针对这种情况动态构建的。您可以像这样迭代键:
def nesting(level):
ret = 'value'
for l in range(level, 0, -1):
ret = {'key%d' % l: ret}
return ret
将范围(…)
片段替换为按所需顺序生成键的代码。因此,如果我们假设键是捕获的组,则应按如下方式更改函数:
def nesting(match): # `match' is a match object like your `m' variable
ret = 'value'
for key in match.groups():
ret = {key: ret}
return ret
如果要按相反顺序获取密钥,请使用反向(match.groups())
def nesting(level, l=None):
# assuming `m` is accessible in the function
if l is None:
l = level
if level == 1:
return {m[l-level]: 'some_value'}
return {m[l-level]: nesting(level-1, l)
对于合理的级别
s,这不会超过递归深度。这也是假设值始终相同,并且m
的形式为:
['key1', 'key2', ...]
此函数的迭代形式可以这样编写:
def nesting(level):
# also assuming `m` is accessible within the function
d = 'some_value'
l = level
while level > 0:
d = {m[l-level]: d}
level -= 1
return d
或:
你想解决什么问题?这似乎有点复杂。你考虑过递归吗?@Greg,Python中的递归应该尽可能避免:)看起来键(捕获的组?)存储在一个简单的列表中,因此,它们可以通过一个简单的循环进行遍历。我需要这样来实现方法,如中所述:它不是用多个键创建dictoinary,而是始终创建单键值字典
def nesting(level):
# also assuming `m` is accessible within the function
d = 'some_value'
l = level
while level > 0:
d = {m[l-level]: d}
level -= 1
return d
def nesting(level):
# also assuming `m` is accessible within the function
d = 'some_value'
for l in range(level, 0, -1): # or xrange in Python 2
d = {m[l-level]: d}
return d