Python (Scripting) - Write dictionary to YAML file

by
Jeremy Canfield |
Updated: August 29 2023
| 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