动态嵌套python字典

时间:2013-02-07 07:17:37

标签: python dictionary

我想创建一个在python字典中创建动态嵌套级别的函数。 例如如果我调用我的函数嵌套,我想要输出如下:

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 个答案:

答案 0 :(得分: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())

答案 1 :(得分: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 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

或者:

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