How to Add Keys and Values to an Exisisting YAML with PyYAML

I found it rather harder than I thought to add key and value to YAML with Python. For example…

You have a YAML file like the following.


And you want to add key1, value1 and key2, value2 and key3, value3 under the root node. I had thought it would be quite as simple as appending child nodes but it turned out that I spent a few hours to figure it out.

The goal YAML I would like in this example is the following.

    key1: value1
    key2: value2
    key3: value3

Here is what you do to achieve it.

import io
import yaml

if __name__ == '__main__':
    with open("data.yaml", 'r') as stream:
        data_loaded = yaml.safe_load(stream)
        additional_data = {"key1": "value1", "key2": "value2", "key3": "value3"}
        for key, value in additional_data.items():
            if data_loaded['root'] is None:
                data_loaded['root'] = {key: value}
                data_loaded['root'].update({key: value})

        with'data.yaml', 'w', encoding='utf8') as outfile:
            yaml.dump(data_loaded, outfile, default_flow_style=False, allow_unicode=True)

There might be simpler solutions but that’s what I came up with and it does what I want it to.

If you add an array data, then the YAML outcome would look like this, which is OK if it meets your requirement but it didn’t mine.

- key1: value1
- key2: value2
- key3: value3

Leave a Reply

Your email address will not be published.