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

Python中如何将指定嵌套列表转换为目标结构的嵌套字典?

转换嵌套列表为嵌套字典的正确实现方法

原始输入与目标结构

原始嵌套列表

json_data = [[[[[[[[[[[['{{app.elastic.hostname}}'], 'hostname:'],
          [['{{app.elastic.scheduleDuration}}'], 'scheduleDuration:'],
          [['{{app.elastic.dataDuration}}'], 'dataDuration:'],
          [['{{app.elastic.displaySummary}}'], 'displaySummary:'],
          [['{{app.elastic.recordSize}}'], 'recordSize:']]]],
       'elastic:']]]],
   'app:'],
  [[[[[[[[[['{{spring.profiles.active}}'], 'active:']]]], 'profiles:'],
      [[[[[['{{spring.redis.host}}'], 'host:'],
          [[[[[['{{spring.redis.sentinel.master}}'], 'master:'],
              [['{{spring.redis.sentinel.nodes}}'], 'nodes:']]]],
           'sentinel:'],
          [['{{spring.redis.password}}'], 'password:'],
          [['{{spring.redis.port}}'], 'port:']]]],
       'redis:']]]],
   'spring:']]]

目标嵌套字典

target_dict = {
    "app": {
      "elastic": {
        "hostname": "{{app.elastic.hostname}}",
        "scheduleDuration": "{{app.elastic.scheduleDuration}}",
        "dataDuration": "{{app.elastic.dataDuration}}",
        "displaySummary": "{{app.elastic.displaySummary}}",
        "recordSize": "{{app.elastic.recordSize}}"
      }
    },
    "spring": {
      "profiles": {
        "active": "{{spring.profiles.active}}"
      },
      "redis": {
        "host": "{{spring.redis.host}}",
        "sentinel": {
          "master": "{{spring.redis.sentinel.master}}",
          "nodes": "{{spring.redis.sentinel.nodes}}"
        },
        "password": "{{spring.redis.password}}",
        "port": "{{spring.redis.port}}"
      }
    }
}

原函数问题分析

你编写的递归函数存在以下问题:

  • 未识别输入的结构规律:每个层级的最后一个元素是带冒号的键名,前面的元素是该键对应的子内容
  • 递归时直接使用update会导致嵌套层级丢失,无法建立父子键值关系
  • 处理字符串时仅创建空字典,未关联对应的模板变量值

正确递归实现

def gen_final_json(list_obj):
    # 处理模板变量列表,直接返回变量值
    if isinstance(list_obj, list) and len(list_obj) == 1 and isinstance(list_obj[0], str) and "{{" in list_obj[0]:
        return list_obj[0]
    
    result = {}
    for item in list_obj:
        if isinstance(item, list):
            # 识别[子内容, 键名:]的结构
            if len(item) >= 2 and isinstance(item[-1], str) and item[-1].endswith(":"):
                key = item[-1].rstrip(":")
                # 递归处理子内容作为键对应的值
                value = gen_final_json(item[:-1])
                result[key] = value
            else:
                # 处理包含多组键值对的子列表,合并结果
                sub_result = gen_final_json(item)
                if isinstance(sub_result, dict):
                    result.update(sub_result)
    return result

final_dict = gen_final_json(json_data)
import json
print(json.dumps(final_dict, indent=2))

代码说明

  1. 模板变量处理:遇到['{{xxx}}']这种结构时,直接返回内部的模板字符串
  2. 层级键处理:识别每个列表末尾的带冒号字符串,去掉冒号作为键,递归处理列表前面的内容作为对应值
  3. 多键值对合并:处理包含多组键值对的子列表时,将递归得到的子字典合并到当前结果中

执行上述代码后,输出结果与目标结构完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 22:40:30