Python3使用pyyaml解析含列表字典的YAML并提取指定角色步骤
问题根因
加载后的baseConfig['role-templates']是列表结构,每个元素是仅包含1个键值对的字典,键为角色名,值为对应的步骤列表,无法直接用角色名作为索引取值。
解决方案
方案1:基础遍历实现(无额外依赖)
直接遍历列表匹配对应角色名,逻辑简单易读:
import yaml with open('dbconfig.yaml') as f: baseConfig = yaml.safe_load(f) role_type = 'readonly' role_steps = None for role_item in baseConfig['role-templates']: if role_type in role_item: role_steps = role_item[role_type] break # 可自行添加角色不存在的异常处理 print(role_steps)
方案2:使用first_true实现
需要先导入itertools模块的first_true方法,调整匹配逻辑即可:
import yaml from itertools import first_true with open('dbconfig.yaml') as f: baseConfig = yaml.safe_load(f) role_type = 'readonly' matched_role = first_true(baseConfig['role-templates'], default=None, pred=lambda x: role_type in x) role_steps = matched_role[role_type] if matched_role is not None else None
优化建议(频繁查询场景)
如果需要多次查询不同角色的步骤,建议提前将列表结构转换为字典,后续查询时间复杂度为O(1),效率更高:
# 初始化时转换一次结构 role_template_map = {} for item in baseConfig['role-templates']: role_template_map.update(item) # 后续直接用角色名查询 role_steps = role_template_map.get(role_type)
内容的提问来源于stack exchange,提问作者rboarman
相关产品推荐
相关产品推荐

