在python中列出嵌套字典 [英] List to nested dictionary in python

查看:135
本文介绍了在python中列出嵌套字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表如下

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

我想从上面的列表中构建一个字典如下

I want to construct a dictionary from the above list as follows

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

列表中的项目数量是动态的。字典将是一个嵌套字典,直到它到达列表的最后一个元素。
python有没有办法这样做?

The number of items in the list is dynamic. The dictionary will be a nested dictionary till it reaches the last element of the list. Is there any way in python to do this?

推荐答案

简单单行:

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

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

For better understanding the above code can be expanded to:

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'}}}

这篇关于在python中列出嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆