Search code examples
pythonpython-3.xdictionarypyyaml

Converting and writing a dictionary to YAML format


I'm retrieving the names of all the columns in each table from a database and create a dictionary where table name is the key and value is a list of column names in that table.

my_dict = {
    'table_1': ['col_1', 'col_2', 'col_3', 'col_4']
}

I'm trying to convert and write the above dictionary into YAML format in a .yml file

I want my output in YAML file to be as:

tables:
  - name: table_1
    columns:
      - name: col_1
      - name: col_2
      - name: col_3
      - name: col_4

My try:

import yaml
import ruamel.yaml as yml

def to_yaml():
    my_dict = {
    'table_1' : ['col_1', 'col_2', 'col_3', 'col_4']
    }

    my_file_path = "/Users/Desktop/python/tables_file"

    with open(f"{my_file_path}/structure.yml", "w") as file:
    yaml.dump(yaml.load(my_dict), default_flow_style=False)

if __name__ == '__main__'
    to_yaml()

The above code didn't give the expected output. I also tried different approaches based on some YAML related Stack Overflow posts but couldn't get it work.


Solution

  • Use:

    import yaml
    import ruamel.yaml
    
    def to_yaml():
        my_dict = {
        'table_1' : ['col_1', 'col_2', 'col_3', 'col_4']
        }
    
        my_file_path = "/Users/Desktop/python/tables_file"
    
        with open(f"{my_file_path}/structure.yml", "w") as file:
            # yaml.dump need a dict and a file handler as parameter
            yaml = ruamel.yaml.YAML()
            yaml.indent(sequence=4, offset=2)
            yaml.dump(my_dict, file)
    
    if __name__ == '__main__':
        to_yaml()
    

    Content of structure.yml:

    table_1:
      - col_1
      - col_2
      - col_3
      - col_4
    

    If you want your expected output, you need to change the structure of your dict. There is nothing magical here.