def find_title_and_path(data, key, path=None, level=0): if path is None: path = [] if 'key' in data and data['key'] == key: # 当前层级的title加入路径 path.append((data['title'])) return data['title'], level, path elif 'children' in data: for child in data['children']: title, child_level, updated_path = find_title_and_path(child, key, path + [(data['title'])], level + 1) if title is not None: return title, child_level, updated_path return None, -1, path # 示例数据 data = { "title": "数据标准", "key": "100", "value": "100", "dscatalog_parent_id": "0", "children": [ { "title": "基础标准", "key": "101", "value": "101", "dscatalog_parent_id": "100", "children": [ {"title": "客户", "key": "104", "value": "104", "dscatalog_parent_id": "101"}, {"title": "客户基础信息", "key": "105", "value": "105", "dscatalog_parent_id": "101"}, {"title": "账户", "key": "106", "value": "106", "dscatalog_parent_id": "101"}, {"title": "账户基础信息", "key": "107", "value": "107", "dscatalog_parent_id": "101"} ] }, { "title": "指标标准", "key": "102", "value": "102", "dscatalog_parent_id": "100", "children": [ {"title": "风险", "key": "103", "value": "103", "dscatalog_parent_id": "102"} ] } ] } # 测试函数 key_to_find = "106" title, level, path = find_title_and_path(data, key_to_find) if {level} == 2 : std_pri_clas = path[0] std_scd_clas = path[1] std_thre_clas = path[2] if {level} == 1 : std_pri_clas = path[0] std_scd_clas = path[1] std_thre_clas = None if {level} == 0 : std_pri_clas = path[0] std_scd_clas = None std_thre_clas = None else: pass # if title: # print(f"The title with key '{key_to_find}' is '{title}' and it is at level {level}.") # print("Path:") # for title in path: # print(f"{title}") # else: print(f"No title found for key '{key_to_find}'.")