Python如何通过字符串形式的嵌套键获取多层dict的对应值
报错原因
你把framework["challenger"]整个字符串当成了单个顶层键去查询字典s,但s的顶层键只有framework,不存在名称为framework["challenger"]的键,因此触发KeyError。
解决方案
方案1(最推荐,无安全风险,易维护)
不要把嵌套访问的表达式存为字符串,改为把嵌套路径存为元组,搭配通用的嵌套取值函数使用:
s={"framework": {"challenger": { "logo.qvg": "50c137c8199d0a807bc31b5c384e67d6c1c0837061bd7d39ed15943b"}}} # 单个层级的键存字符串,多层级的键存为元组 possible_folders=["tractor","svg","framework","common", ("framework", "challenger")] def get_nested(data, path): if isinstance(path, str): return data.get(path) res = data for key in path: if not isinstance(res, dict) or key not in res: return None res = res[key] return res print(get_nested(s, possible_folders[-1]))
方案2(兼容现有字符串格式,无安全风险)
如果无法修改possible_folders的存储格式,可以用正则从字符串中提取所有键名,再逐层取值:
import re s={"framework": {"challenger": { "logo.qvg": "50c137c8199d0a807bc31b5c384e67d6c1c0837061bd7d39ed15943b"}}} possible_folders=["tractor","svg","framework","common",'framework["challenger"]'] def get_nested_from_str(data, path_str): # 提取字符串中所有的键名 keys = re.findall(r'"([^"]+)"|(\w+)', path_str) keys = [k for item in keys for k in item if k] res = data for key in keys: if not isinstance(res, dict) or key not in res: return None res = res[key] return res print(get_nested_from_str(s, possible_folders[-1]))
方案3(仅可用于完全可信的字符串来源)
如果只是临时调试,且完全确认字符串来源安全,没有恶意代码注入风险,可以直接用eval执行表达式:
s={"framework": {"challenger": { "logo.qvg": "50c137c8199d0a807bc31b5c384e67d6c1c0837061bd7d39ed15943b"}}} possible_folders=["tractor","svg","framework","common",'framework["challenger"]'] print(eval(f"s{possible_folders[-1].removeprefix('framework')}", {"__builtins__": {}}, {"s": s["framework"]}))
内容的提问来源于stack exchange,提问作者Adrian Vulpeanu
相关产品推荐
相关产品推荐

