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

如何在Python中扁平化给定字典?代码调试与预期输出

Python嵌套字典扁平化实现方法

你的代码存在几个关键问题导致无法得到预期结果:

  • 仅打印零散的键值对或内层字典,没有将结果整合为一个完整的扁平化字典
  • 仅处理了两层嵌套结构,无法应对更深层级的嵌套
  • 内层循环中错误打印v_outer,没有将内层字典的键值对提取到最终结果中

以下是可以实现需求的递归解法,支持任意层级的嵌套字典:

from collections.abc import Mapping

my_dict = {'abc': 'abc', 'def': {'ghi': 'ghi', 'jkl': 'jkl'}}

def flatten_dict(in_dict):
    flattened = {}
    if isinstance(in_dict, Mapping):
        for key, value in in_dict.items():
            # 递归处理嵌套字典,合并结果
            if isinstance(value, Mapping):
                flattened.update(flatten_dict(value))
            else:
                flattened[key] = value
    return flattened

# 调用函数并输出结果
result = flatten_dict(my_dict)
print(result)
# 输出: {'abc': 'abc', 'ghi': 'ghi', 'jkl': 'jkl'}

代码说明:

  1. 初始化空字典flattened用于存储最终的扁平化结果
  2. 遍历输入字典的每个键值对:
    • 如果值是字典类结构(Mapping类型),递归调用flatten_dict处理该嵌套字典,并用update方法将递归返回的扁平化内容合并到结果中
    • 如果值不是字典类型,直接将当前键值对添加到结果字典
  3. 函数最终返回完整的扁平化字典

如果需要保留父键的前缀(例如将def.ghi转为def_ghi作为新键),可以修改函数为:

def flatten_dict_with_prefix(in_dict, parent_key='', sep='_'):
    flattened = {}
    if isinstance(in_dict, Mapping):
        for key, value in in_dict.items():
            new_key = f"{parent_key}{sep}{key}" if parent_key else key
            if isinstance(value, Mapping):
                flattened.update(flatten_dict_with_prefix(value, new_key, sep))
            else:
                flattened[new_key] = value
    return flattened

# 调用示例
result = flatten_dict_with_prefix(my_dict)
print(result)
# 输出: {'abc': 'abc', 'def_ghi': 'ghi', 'def_jkl': 'jkl'}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 00:25:20