如何从嵌套字典(JSON)提取键路径与底层值,避免层级错误?
解决方案:递归提取嵌套字典的键路径与底层值
我来帮你解决这个嵌套字典的提取问题——递归是处理这种不确定层级结构的完美方案,刚好能满足你收集键路径和底层值的需求,还能避免固定层级循环带来的报错问题。
完整实现代码
import os import json def extract_paths_and_values(data, current_path=None): # 初始化结果容器(仅首次调用时创建) if current_path is None: current_path = [] keys_list = [] values_list = [] for key, value in data.items(): # 复制当前路径,避免递归修改原列表 new_path = current_path.copy() # 仅将非空键加入路径(匹配你期望的输出格式) if key != "": new_path.append(key) if isinstance(value, dict): # 递归处理子字典,传递更新后的路径 extract_paths_and_values(value, new_path) else: # 遇到底层元素(字符串/列表),存入结果 keys_list.append(new_path) values_list.append(value) # 仅首次调用时返回最终结果 if current_path == []: return keys_list, values_list # 读取并处理文件夹中的JSON文件 folder = "shared/" files = os.listdir(folder) all_keys = [] all_values = [] for filename in files: # 用os.path.join安全拼接路径,适配不同操作系统 file_path = os.path.join(folder, filename) print(f"正在处理文件: {file_path}") with open(file_path, 'r') as f: data = json.load(f) # 提取当前文件的键路径和值 file_keys, file_values = extract_paths_and_values(data) all_keys.extend(file_keys) all_values.extend(file_values) # 输出最终结果 print("\n提取结果:") print(f"keys = {all_keys}") print(f"value = {all_values}")
代码工作原理
递归核心逻辑:
- 函数
extract_paths_and_values会逐层遍历字典:遇到非空键就加入当前路径,空键则跳过(完全匹配你期望的socks路径格式)。 - 如果当前值仍是字典,就递归进入下一层;如果是字符串或列表(底层元素),就把当前路径和对应值存入结果列表。
- 用列表复制(
current_path.copy())避免递归过程中修改原路径列表,保证每个路径的独立性。
- 函数
文件处理优化:
- 用
os.path.join拼接路径,比直接字符串相加更可靠,能自动适配Windows/Linux的路径分隔符差异。 - 支持批量处理文件夹中的所有JSON文件,结果会合并到
all_keys和all_values中。
- 用
验证结果
用你提供的JSON输入测试,会得到完全符合期望的输出:
keys = [["shortshirt","ralphlauren","classic"],["socks"]] value = [['That Ralph Lauren classic fit is a timeless look!', 'Nice choice. Can’t go wrong with Ralph Lauren'], ['Have to find the right socks to keep your feet cozy']]
边界情况兼容
- 处理单个字符串底层值(比如
{"a": "hello"}),会得到keys = [["a"]],value = ["hello"]。 - 处理多层空键嵌套(比如
{"a": {"": {"": "test"}}}),会得到keys = [["a"]],value = ["test"]。 - 处理同一层级多非空键(比如
{"a": {"b": ["x"], "c": ["y"]}}),会得到keys = [["a","b"], ["a","c"]],value = [["x"], ["y"]]。
内容的提问来源于stack exchange,提问作者Asim
相关产品推荐
相关产品推荐

