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

如何从嵌套字典提取值为整数的键值对并保持原有顺序?

嵌套字典扁平化实现

给定嵌套字典:

dict_nested = {"A":{"C":100, "D":{"E":100, "F":100}}, "B":200}

期望得到扁平化后的字典,仅保留值为整数的键值对,且保持原有顺序:

dict_result = {"C":100, "E":100, "F":100, "B":200}

实现代码

def flatten_dict(nested_dict):
    result = {}
    for key, value in nested_dict.items():
        if isinstance(value, dict):
            # 递归处理嵌套字典,合并结果
            result.update(flatten_dict(value))
        elif isinstance(value, int):
            # 仅保留值为整数的键值对
            result[key] = value
    return result

# 测试
dict_nested = {"A":{"C":100, "D":{"E":100, "F":100}}, "B":200}
dict_result = flatten_dict(dict_nested)
print(dict_result)  # 输出: {'C': 100, 'E': 100, 'F': 100, 'B': 200}

说明

  • 用递归方式遍历嵌套字典的每一层,遇到子字典就继续深入解析
  • 仅当值为整数类型时,才将键值对加入结果字典
  • Python 3.7及以上版本的字典默认保留插入顺序,因此结果会严格遵循原始字典中键值对的出现顺序

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 06:24:22