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

如何将字典中带点分隔的相似键转换为嵌套字典

将带点分隔键的字典转换为嵌套字典

问题描述

给定一个字典,其中部分键以“.”作为层级分隔符,需要把拥有共同前缀的键合并为子字典,示例如下:

输入字典:

d = {"book.title": "abc", "book.content": "def", "author": "ghi"}

预期输出:

{"book": {"title": "abc", "content": "def"}, "author": "ghi"}

原生Python实现

无需依赖第三方库,直接通过遍历拆分键来构建嵌套结构:

def flatten_to_nested(d):
    result = {}
    for key, value in d.items():
        # 拆分键为层级列表
        key_parts = key.split('.')
        current_level = result
        # 遍历除最后一层外的所有层级,创建子字典
        for part in key_parts[:-1]:
            if part not in current_level:
                current_level[part] = {}
            current_level = current_level[part]
        # 设置最后一层的键值对
        current_level[key_parts[-1]] = value
    return result

# 测试代码
d = {"book.title": "abc", "book.content": "def", "author": "ghi"}
print(flatten_to_nested(d))

运行后即可得到预期的嵌套字典。


第三方库简化实现(可选)

如果项目中已经引入python-box库,可以用更简洁的方式处理:

from box import Box

d = {"book.title": "abc", "book.content": "def", "author": "ghi"}
nested_dict = Box(d, box_dots=True).to_dict()
print(nested_dict)

python-box会自动解析带点的键,快速生成嵌套字典,适合追求开发效率的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 05:53:08