列出要在python中嵌套的字典

娜迦·拉克希米

我有一个清单如下

['item1', 'item2', 'item3', 'item4']

我想从上面的列表中构造一个字典,如下所示

{
    "item1": {
        "item2": {
            "item3": "item4"
        }
    }
}

列表中的项目数是动态的。该字典将是嵌套的字典,直到到达列表的最后一个元素。python中有什么方法可以做到这一点吗?

埃尔莫·范·基尔莫

简单的一线:

a = ['item1', 'item2', 'item3','item4']
print reduce(lambda x, y: {y: x}, reversed(a))

为了更好地理解,以上代码可以扩展为:

def nest_me(x, y):
    """
    Take two arguments and return a one element dict with first
    argument as a value and second as a key
    """
    return {y: x}

a = ['item1', 'item2', 'item3','item4']
rev_a = reversed(a) # ['item4', 'item3', 'item2','item1']
print reduce(
    nest_me, # Function applied until the list is reduced to one element list
    rev_a # Iterable to be reduced
)
# {'item1': {'item2': {'item3': 'item4'}}}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章