在python中列出嵌套字典

编程入门 行业动态 更新时间:2024-10-24 18:27:36
本文介绍了在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中列出嵌套字典

本文发布于:2023-11-12 03:41:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1580409.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   字典   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!