简体   繁体   English

使用 python 创建 yaml 文件 - 列表格式

[英]Using python to create a yaml file - list formatting

I have a python script that outputs a yaml file using yaml.dump(yaml_dict, file_path)我有一个 python 脚本,它使用yaml.dump(yaml_dict, file_path)输出 yaml 文件

The output is formatted something like this: output 的格式如下:

name: joe
type: builder
tables:
- table_name_1:
    exclusion:
    - column_a
    - column_b
    site: location_c
- table_name_2:
    exclusion:
    - column_d
    site: location_b

This is very close to how I want the output to look, but slightly out in terms of the formatting of the table names.这与我希望 output 的外观非常接近,但在表名的格式方面略有不同。 This is what I want:这就是我要的:

name: joe
type: builder
tables:
  table_name_1:
    exclusion:
    - column_a
    - column_b
    site: location_c
  table_name_2:
    exclusion:
    - column_d
    site: location_b

That is, I want no hyphen before the list of tables, instead I just want the indentation via spaces.也就是说,我不想在表格列表之前使用连字符,而只需要通过空格进行缩进。

The code I am using to add the tables to the yaml_dict is as follows:我用来将表添加到yaml_dict的代码如下:

table_list = df['table'].tolist()
    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
        table_dict = {table: table_config}
        yaml_dict['tables'].append(table_dict)

I am happy to keep the hyphens in the list of exclusions, but I don't want them in the list of tables.我很高兴将连字符保留在排除列表中,但我不希望它们出现在表格列表中。 Is there anything I can do to remove them?我能做些什么来删除它们吗?

The dashes mean that you are ouputing a list.破折号表示您正在输出一个列表。 Instead, you need a dict.相反,你需要一个字典。

Assuming you initialize it something like this:假设你初始化它是这样的:

yaml_dict['tables'] = {}

Then in the for loop:然后在for循环中:

yaml_dict['tables'].update(table_dict)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM