遍历嵌套字典与列表混合对象,筛选指定字段
问题描述
我有一个由字典和列表嵌套组成的对象:
sample_data = { "field_1": "aaa", "field_2": [ { "name": "bbb", "field_4": "ccc", "field_need_to_filter": False, }, { "name": "ddd", "details": [ { "name": "eee", "details": [ { "name": "fff", "field_10": { "field_11": "rrr", "details": [ { "name": "xxx", "field_need_to_filter": True, }, { "name": "yyy", "field_need_to_filter": True, }, { "field_13": "zzz", "field_need_to_filter": False, } ] } } ] } ] } ] }
需要遍历该对象,收集所有field_need_to_filter为True的节点对应的name字段,按层级用点连接成路径。预期输出为:["ddd.eee.fff.xxx", "ddd.eee.fff.yyy"]
解决方案
可以用递归遍历的方式处理嵌套结构,追踪当前层级的name路径,遇到符合条件的节点就记录完整路径:
def collect_filtered_names(data, current_path=None): result = [] if current_path is None: current_path = [] # 处理字典类型 if isinstance(data, dict): # 如果当前节点有name字段,加入路径 if "name" in data: current_path = current_path + [data["name"]] # 检查当前节点是否符合过滤条件 if data.get("field_need_to_filter") is True: result.append(".".join(current_path)) # 递归遍历字典的所有值 for value in data.values(): result.extend(collect_filtered_names(value, current_path.copy())) # 处理列表类型 elif isinstance(data, list): for item in data: result.extend(collect_filtered_names(item, current_path.copy())) return result # 测试示例数据 output = collect_filtered_names(sample_data) print(output) # 输出: ['ddd.eee.fff.xxx', 'ddd.eee.fff.yyy']
代码说明
- 递归函数
collect_filtered_names接收两个参数:当前遍历的数据data,以及当前追踪的name路径current_path - 遇到字典时,若存在
name字段则更新路径;若field_need_to_filter为True,则将当前路径用点连接后加入结果列表 - 遇到列表时,遍历每个元素继续递归
- 使用
current_path.copy()确保每次递归的路径不会互相干扰,避免路径错误拼接
内容的提问来源于stack exchange,提问作者wawawa
相关产品推荐
相关产品推荐

