5/28/2023

yaml to Dict and update element like class and save dict to yaml again, python example code

refer to code and example yaml



.

before yaml to run code

a: a-value
b: b-value
c:
d: Nested
e: Values

..


code

pip install yaml, attract

.

import yaml
from attrdict import AttrDict

# Load YAML file
with open('file.yaml', 'r') as f:
data = yaml.safe_load(f)

# Convert to AttrDict for dot notation access
data = AttrDict(data)

# Access elements
print(data.a)
print(data.b)

# Modify elements
data.a = 'new value 2'
data.b = 'another new value 2'

# Convert back to dictionary
data = dict(data)

# Save back to YAML
with open('file.yaml', 'w') as f:
yaml.safe_dump(data, f)

..


.

after yaml running code

a: new value 2
b: another new value 2
c:
d: Nested
e: Values

..



Thank you.

www.marearts.com

๐Ÿ™‡๐Ÿป‍♂️

No comments:

Post a Comment