如何用无全局变量的递归方法反转嵌套字典/列表层级
嵌套字典反转的递归实现(无全局变量)
需求说明
需要将给定的嵌套字典(包含列表结构)进行反转,要求使用递归方法实现,且不使用全局变量存储结果。
输入示例
{ "a": { "b1": { "c": { "value": "c_value", "children": { "d": "d_value" } } }, "b2": [ "b2_1", { "b2_2_1": 2, "b2_2_2": { "b2_2_2_1": "b2_2_2_1_value", "b2_2_2_2": "b2_2_2_2_value" } }, 3 ] } }
期望输出
{ "d": { "children": { "c": { "b2": [ 3, { "b2_2_2": { "b2_2_2_2": "b2_2_2_2_value", "b2_2_2_1": "b2_2_2_1_value" }, "b2_2_1": 2 }, "b2_1" ], "b1": { "a": "d_value" } } }, "value": "c_value" } }
递归实现方案
通过嵌套辅助递归函数,利用参数传递状态和返回值传递结果的方式,避免使用全局变量。核心思路是根据节点类型(字典/列表/普通值)分别处理,递归构建反转后的结构:
def reverse_structure(data): def helper(node, path): """递归辅助函数,返回反转后的结构片段""" if isinstance(node, dict): reversed_items = list(reversed(node.items())) attrs = {} child_result = None for key, value in reversed_items: if key == "children": # 处理路径延伸的children分支,传递当前节点和路径 child_result = helper(value, [(key, node)] + path) else: # 处理普通属性,递归处理子元素 if isinstance(value, list): attrs[key] = [helper(item, []) for item in reversed(value)] elif isinstance(value, dict): attrs[key] = helper(value, []) else: attrs[key] = value if child_result is not None: # 将普通属性合并到children分支的结果中 top_key = next(iter(child_result.keys())) child_result[top_key].update(attrs) # 构建反向路径结构 if path: current_node_key = list(path[0][1].keys())[0] parent_key = path[1][0] if len(path) > 1 else None if parent_key: temp = {current_node_key: child_result[top_key]} child_result[top_key] = {"children": temp} else: child_result[top_key] = {"children": child_result[top_key]} return child_result else: # 无children分支,直接返回反转后的字典 return attrs elif isinstance(node, list): # 反转列表并递归处理每个元素 return [helper(item, []) for item in reversed(node)] else: # 处理叶子值,构建反向路径 if path: current_key = path[0][0] parent_node = path[0][1] rest_path = path[1:] return {current_key: helper(parent_node, rest_path)} else: return node return helper(data, []) # 测试代码 input_data = { "a": { "b1": { "c": { "value": "c_value", "children": { "d": "d_value" } } }, "b2": [ "b2_1", { "b2_2_1": 2, "b2_2_2": { "b2_2_2_1": "b2_2_2_1_value", "b2_2_2_2": "b2_2_2_2_value" } }, 3 ] } } # 格式化输出结果 import json print(json.dumps(reverse_structure(input_data), indent=2))
代码说明
- 辅助函数
helper:承担核心递归逻辑,接收当前节点和路径信息,返回反转后的结构片段。 - 字典处理:
- 反转字典的键遍历顺序,区分
children路径分支和普通属性。 - 普通属性会被递归处理(列表反转、子字典反转)后收集,最终合并到
children分支的结果中。 children分支递归处理后,构建反向路径结构,将父节点依次挂载到子节点下。
- 反转字典的键遍历顺序,区分
- 列表处理:直接反转列表,再递归处理每个元素。
- 叶子值处理:根据积累的路径信息,构建从叶子键到根节点的反向路径结构。
内容的提问来源于stack exchange,提问作者kairos
相关产品推荐
相关产品推荐

