将列表转换为嵌套字典 [英] Converting list to nested dictionary

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

问题描述

如何将列表转换成嵌套的`字典'?

How can I convert a list into nested `dictionary'?

例如:

l = [1, 2, 3, 4] 

我想把它转换成一个如下所示的字典:

I'd like to convert it to a dictionary that looks like this:

{1: {2: {3: {4: {}}}}}


推荐答案

您还可以使用 functools.reduce 为此。

You could also use functools.reduce for this.

reduce(lambda cur, k: {k: cur}, reversed(l), {})

演示

>>> from functools import reduce
>>> l = [1, 2, 3, 4]

>>> reduce(lambda cur, k: {k: cur}, reversed(l), {})
{1: {2: {3: {4: {}}}}}






建筑流程看起来像


The flow of construction looks something like

{4: {}} -> {3: {4: {}} -> {2: {3: {4: {}}}} -> {1: {2: {3: {4: {}}}}}

as reduce 遍历反向迭代器,创建一个新的单元素dict。

as reduce traverses the reverse iterator making a new single-element dict.

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

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