Python如何将嵌套字典扁平化输出为路径值对应的列表嵌套列表结构
嵌套字典扁平化输出全路径列表解决方案
问题原因
你原有代码的核心问题是没有对不同路径做分支隔离,所有节点的键和值都被添加到同一个一维列表中,最终自然无法得到按路径拆分的嵌套列表结构。
修改后实现代码
如果是类内方法,可直接使用如下实现:
def change(self, tree, current_path=None): if current_path is None: current_path = [] res = [] for key, value in tree.items(): temp_path = current_path + [key] if isinstance(value, dict): res.extend(self.change(value, temp_path)) else: res.append(temp_path + [value]) return res
调用&输出示例
假设你持有的嵌套字典为data,调用方法后得到的输出如下:
# 调用 result = self.change(data) # 输出 [ ['weather', 'cloudy', 'yes'], ['weather', 'rainy', 'wind', 'strong', 'no'], ['weather', 'rainy', 'wind', 'weak', 'yes'], ['weather', 'sunny', 'humidity', 'high', 'no'], ['weather', 'sunny', 'humidity', 'normal', 'yes'] ]
实现逻辑说明
- 递归时携带
current_path参数跟踪当前遍历的路径前缀 - 每遍历到一个键,就将其追加到当前路径前缀中生成临时路径
- 如果对应值是字典,就将临时路径作为前缀传入递归调用,将返回的子路径列表合并到结果中
- 如果对应值是叶子节点(非字典),就将值追加到临时路径末尾,作为完整路径子列表加入结果
- 这里用
isinstance判断类型比type(value) is dict兼容性更好,可支持dict子类的判断
内容的提问来源于stack exchange,提问作者WholesomeGhost
相关产品推荐
相关产品推荐

