有没有优雅的方法在python中构建一个多级字典?

wai*_*kuo 5 python dictionary

我想构建一个多级字典,如:

A = { 
    'a': {
        'A': {
            '1': {}, 
            '2': {}, 
        },  
        'B': {
            '1': {}, 
            '2': {}, 
        },  
    },  
    'b': {
        'A': {
            '1': {}, 
            '2': {}, 
        },  
        'B': {
            '1': {}, 
            '2': {}, 
        },  
    },  
}
Run Code Online (Sandbox Code Playgroud)

我的问题是它是否存在一个函数,我可以通过以下方式构建上述用语:

D = function(['a', 'b'], ['A', 'B'], ['1', '2'], {})
Run Code Online (Sandbox Code Playgroud)

mat*_*att 6

这使用复制功能允许您指定不同的叶节点.否则所有叶子将指向同一个字典.

from copy import copy

def multidict(*args):
    if len(args) == 1:
        return copy(args[0])
    out = {}
    for x in args[0]:
        out[x] = multidict(*args[1:])
    return out

print multidict(['a', 'b'], ['A', 'B'], ['1', '2'], {})
Run Code Online (Sandbox Code Playgroud)


eum*_*iro 5

def multi(*args):
    if len(args) > 1:
        return {arg:multi(*args[1:]) for arg in args[0]}
    else:
        return args[0]

multi(['a', 'b'], ['A', 'B'], ['1', '2'], {})
Run Code Online (Sandbox Code Playgroud)

回报

{'a': {'A': {'1': {}, '2': {}}, 'B': {'1': {}, '2': {}}},
 'b': {'A': {'1': {}, '2': {}}, 'B': {'1': {}, '2': {}}}}
Run Code Online (Sandbox Code Playgroud)

编辑:在我的解决方案中,最后一个参数{}将被复制到输出的每个叶子中作为对同一个字典的引用.如果这是一个问题(用不可变对象替换它,例如float,integer或string是另一回事),请使用copy.copy@matt 的想法.