Python如何从yaml嵌套字典提取url并写入另一yaml对应type节点
问题解答
报错原因
AttributeError: 'list' object has no attribute 'items'报错的核心原因是datagen["type"]经YAML解析后为列表类型,而非字典,列表本身不存在items()方法。你提供的两份YAML文件中type字段下均为多个同结构的实例集合,YAML解析后会自动转换为列表存储。
实现方案
该需求完全可以通过Python字典操作实现,操作步骤如下:
- 读取yaml_file1.yaml,构造
function字段和url字段的映射字典,以function值为键,对应url为值 - 读取yaml_file2.yaml,遍历
type列表中的每个实例,通过function值匹配映射字典,将对应url写入实例 - 将修改后的内容写回yaml_file2.yaml
完整可运行代码
首先安装依赖库:pip install pyyaml
import yaml # 提取yaml1中function和url的对应关系 with open('yaml_file1.yaml', 'r', encoding='utf-8') as f1: data1 = yaml.full_load(f1) func_url_map = {} type_list1 = data1['type'] for item in type_list1: func_name = item['function'] func_url_map[func_name] = item['url'] # 给yaml2的对应实例插入url with open('yaml_file2.yaml', 'r', encoding='utf-8') as f2: data2 = yaml.full_load(f2) type_list2 = data2['type'] for item in type_list2: func_name = item['function'] if func_name in func_url_map: item['url'] = func_url_map[func_name] # 写回修改后的yaml2文件 with open('yaml_file2.yaml', 'w', encoding='utf-8') as f_out: # 保持YAML块级缩进格式 yaml.dump(data2, f_out, default_flow_style=False, allow_unicode=True)
格式修正提示
运行代码前需要先修正你提供的YAML示例中的两处格式问题,否则会出现解析错误:
- 所有键值对的冒号后必须加空格,例如
url:"file:///path1"需改为url: "file:///path1" type字段下的每个实例开头要加横杠-标识为列表项,示例如下:
type: - compression: lz function: boot_a # 其余同层级其他字段 - compression: zip function: boot_b # 其余同层级其他字段
内容的提问来源于stack exchange,提问作者Kaytoo
相关产品推荐
相关产品推荐

