使用Python生成YAML文件:移除表项前连字符并调整缩进
解决方案
问题出在你把tables节点定义成了列表(通过append添加元素),YAML里列表项默认会带连字符。要去掉连字符,需要把tables改成字典结构,让每个表名作为字典的键,对应的配置作为值。
修改步骤:
- 确保
yaml_dict中的tables初始化为空字典{},而非空列表[] - 循环中直接将表配置赋值给
tables字典的对应键,不再使用append方法
修改后的代码:
table_list = df['table'].tolist() # 确保tables是字典类型,若之前是列表则重置 if 'tables' not in yaml_dict or isinstance(yaml_dict['tables'], list): yaml_dict['tables'] = {} for table in table_list: table_config = {'site': df.loc[df['table'] == table, 'site'].item()} exclusion = df.loc[df['table'] == table, 'exclusion'].item() er_list = exclusion.replace(' ', '').split(",") table_config['exclusion'] = er_list # 直接以表名为键,将配置存入tables字典 yaml_dict['tables'][table] = table_config
效果对比:
- 修改前的YAML输出(列表格式,带连字符):
tables: - table1: site: xxx exclusion: [a,b,c] - table2: site: yyy exclusion: [d,e,f]
- 修改后的YAML输出(字典格式,无连字符):
tables: table1: site: xxx exclusion: [a,b,c] table2: site: yyy exclusion: [d,e,f]
内容的提问来源于stack exchange,提问作者nimgwfc
相关产品推荐
相关产品推荐

