You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中将元素列表转换为字典的字典(嵌套字典)

将列表转换为层级嵌套字典的几种方法

给定输入列表:

input_list = ['your name', 'mother', 'age', '43']

目标生成的嵌套字典:

result = {'your name': {'mother': {'age': '43'}}}

1. 迭代逆序构建(最直观)

从列表末尾元素开始,逐步向前嵌套包装:

def list_to_nested_dict(lst):
    if len(lst) < 2:
        return {}  # 处理长度不足的边界情况
    current_val = lst[-1]
    # 从倒数第二个元素开始逆序遍历
    for key in reversed(lst[:-1]):
        current_val = {key: current_val}
    return current_val

# 调用示例
input_list = ['your name', 'mother', 'age', '43']
nested_dict = list_to_nested_dict(input_list)
print(nested_dict)

2. 使用functools.reduce简化代码

用reduce函数将迭代逻辑浓缩,适合追求简洁的场景:

from functools import reduce

input_list = ['your name', 'mother', 'age', '43']
nested_dict = reduce(lambda acc, key: {key: acc}, reversed(input_list[:-1]), input_list[-1])
print(nested_dict)

逻辑说明:reduce以列表最后一个元素为初始累积值,逆序遍历前n-1个元素,每次将累积值包装为新字典的value,最终生成嵌套结构。

3. 递归实现

用递归逐步拆解列表,代码逻辑更贴合嵌套结构的层级关系:

def list_to_nested_dict_recursive(lst):
    if len(lst) == 1:
        return lst[0]
    # 取第一个元素为key,剩余列表递归处理后作为value
    return {lst[0]: list_to_nested_dict_recursive(lst[1:])}

# 调用示例
input_list = ['your name', 'mother', 'age', '43']
nested_dict = list_to_nested_dict_recursive(input_list)
print(nested_dict)

内容的提问来源于stack exchange,提问作者user20084690

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 16:20:49