如何从嵌套字典提取值为整数的键值对并保持原有顺序?
嵌套字典扁平化实现
给定嵌套字典:
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
相关产品推荐
相关产品推荐

