Bootstrap FreeKB - Python (Scripting) - Write dictionary to YAML file
Python (Scripting) - Write dictionary to YAML file

Updated:   |  Python (Scripting) articles

Let's say you want to take a dictionary and create a YAML file, perhaps something like this.

domains:
  foo.example.com:
    alias: foo
    region: us-east-1
  bar.example.com:
    alias: bar
    region: us-east-1

 

ruamel.yaml can be used to parse the dictionary into YAML. The pip install command can be used to install the ruamel.yaml package.

pip install ruamel.yaml

 

Or, you can specify the version to install

pip install ruamel.yaml==0.17.32

 

Or, better yet, use a requirements.txt file.

ruamel.yaml==0.17.32

 

And then install the packages using the requirements.txt file.

pip install --requirement requirements.txt

 

And now you can use ruamel.yaml to parse the dictionary into YAML.

#!/usr/bin/python
import ruamel.yaml

dictionary = {'domains': {'foo.example.com': {'alias': 'foo', 'region': 'us-east-1'}, 'bar.example.com': {'alias': 'bar', 'region': 'us-east-1'}}}

yaml = ruamel.yaml.YAML()
yaml.default_flow_style = False

with open("/path/to/example.yml", "w") as file:
  yaml.dump(dictionary, file)

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter e815b5 in the box below so that we can be sure you are a human.