动态嵌套Python字典

1 投票
2 回答
1675 浏览
提问于 2025-04-17 15:04

我想创建一个函数,这个函数可以在Python字典中动态地生成多层嵌套。

比如,如果我调用我的函数nesting,我希望输出的结果像下面这样:

nesting(1)  :  dict = {key1:<value>}
nesting(2)  :  dict = {key1:{key2:<value>}}
nesting(3)  :  dict = {key1:{key2:{key3:<value>}}}

以此类推。在调用这个函数之前,我已经有了所有的键和值,但在执行代码之前并不知道它们。

我把这些键存储在一个变量'm'中,而这个m是通过以下方式获得的:

m=re.match(pattern,string)

这个模式是根据情况动态构建的。

2 个回答

1
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)

对于合理的level值,这个不会超过递归的深度。这里假设值总是相同的,并且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

或者:

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
1

你可以这样遍历键:

def nesting(level):
    ret = 'value'
    for l in range(level, 0, -1):
        ret = {'key%d' % l: ret}
    return ret

range(...)这一部分换成能按照你想要的顺序返回键的代码。如果我们假设这些键是捕获的组,你应该把函数改成这样:

def nesting(match): # `match' is a match object like your `m' variable
    ret = 'value'
    for key in match.groups():
        ret = {key: ret}
    return ret

或者,如果你想要反向获取这些键,可以使用reversed(match.groups())

撰写回答