Bartek Gmerek
Bartek Gmerek

Reputation: 43

Set value for a nested key in YAML

I need a function which will allow setting a nested value in YAML file. For instance, for a YAML like:

I would do something like: update_yaml_value("LEVEL_1.LEVEL_2.LEVEL_3", "new_value")

I'd appreciate any help. Thanks in advance.

Upvotes: 3

Views: 2951

Answers (3)

pouralijan
pouralijan

Reputation: 86

You can use this function to change a dict value recersivly.

test.py:

#!/usr/bin/env python3

import yaml


def change_config(conf, key, value):
    if isinstance(conf, dict):
        for k, v in conf.items():
            if k == key:
                conf[k] = value
            elif isinstance(v, dict):
                change_config(v, key, value)


with open("smth.yaml", "r") as f:
    yaml_data = yaml.load(f, Loader=yaml.Loader)
    print(yaml_data)
    change_config(yaml_data, "level3", "hassan")
    print(yaml_data)

smth.yaml:

level0:
  level1:
    level3: test

Terminal Output:

{'level0': {'level1': {'level3': 'test'}}}
{'level0': {'level1': {'level3': 'hassan'}}}

Upvotes: 0

SimfikDuke
SimfikDuke

Reputation: 1148

First of all you need to import yaml:

import yaml

When you load some yaml file you will get a python dict object.

with open('/path/to/smth.yaml', 'r') as f:
    yaml_data = yaml.safe_load(f)

To have the ability to change it in way you described you can create function like next:

def update_yaml_value(long_key, data):
    keys = long_key.split('.')
    accessable = yaml_data
    for k in keys[:-1]:
        accessable = accessable[k]
    accessable[keys[-1]] = data

And then save this yaml file:

with open('/path/to/smth.yaml', 'w+') as f:
    yaml.dump(yaml_data, f, default_flow_style=False)

Upvotes: 3

balderman
balderman

Reputation: 23815

Your python code will load the YAML into a dict.

With the dict you will be able to update the value.

a_dict = load_yaml() # to be implemented by the OP
a_dict['level_1']['level_2']['level_3'] = 'a_new_value'

Upvotes: 0

Related Questions