简体   繁体   中英

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)

The output is formatted something like this:

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. 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:

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:

yaml_dict['tables'].update(table_dict)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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