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

如何将序列列表转换为多层嵌套字典?求通用实现方案

多层序列转嵌套字典方案

问题描述

给定如下序列列表:

l = [( "tx", 'houston', 'richmond'),
("tx", 'dallas', 'lakewood'),
( "tx", 'houston', 'kessler'),
( "tx", 'dallas', 'cedars'),
( "ct", 'hartford', 'wethersfield'),
( "ct", 'hartford', 'parkville'),
( "ct", 'new haven', 'westville'),
( "fl", 'miami', 'gladview'),
("fl", 'orlando', 'parramore'),
( "fl", 'orlando', 'golden heights'),
( "fl", 'miami', 'el portal')]

需要将其转换为指定格式的嵌套字典,且方案需支持处理任意长度的序列(即多层嵌套场景),最终输出示例如下:

{
    "tx": [
        {"houston": [ "richmond", "kessler" ]},
        { "dallas": [ "lakewood", "cedars" ]},
    ],
    "ct": [
        {"hartford": ["wethersfield", "parkville"]},
        {"new haven": ["westville"]},
    ],
    "fl": [
        {"orlando": ["parramore", "golden heights"]},
        {"miami": ["gladview", "el portal"]},
    ]
}

解决方案

一、自定义通用嵌套函数

以下函数通过递归逻辑处理任意层数的序列,自动完成分组与嵌套构建:

from collections import defaultdict

def build_nested_structure(data):
    # 序列只剩最后一层时,直接返回元素列表
    if len(data[0]) == 1:
        return [item[0] for item in data]
    
    # 按当前层级的第一个元素分组
    level_groups = defaultdict(list)
    for item in data:
        level_groups[item[0]].append(item[1:])
    
    result = {}
    for key, subgroups in level_groups.items():
        # 下一层是最后一层时,整理为{键: 元素列表}的字典并放入列表
        if len(subgroups[0]) == 1:
            inner_dict = defaultdict(list)
            for k, v in subgroups:
                inner_dict[k].append(v)
            result[key] = [{k: v} for k, v in inner_dict.items()]
        # 否则继续递归处理更深层级
        else:
            result[key] = [build_nested_structure(subgroups)]
    
    return result

# 调用示例
output = build_nested_structure(l)
print(output)

二、使用Pandas实现

借助Pandas的分组功能可快速完成格式转换,代码简洁直观:

import pandas as pd

# 将列表转为DataFrame
df = pd.DataFrame(l, columns=['state', 'city', 'area'])

# 先按state和city分组,收集area为列表
grouped = df.groupby(['state', 'city'])['area'].apply(list).reset_index()

# 再按state分组,整理为目标嵌套格式
result = grouped.groupby('state').apply(
    lambda x: x.set_index('city')['area'].to_dict('records')
).to_dict()

print(result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 12:25:33