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

🙇🏻‍♂️

yaml to dict, adding argparse to dict (easydict, yaml)

 

Simple code to adapt and know how to read yaml and convert it to dict.

And one more thing is add argparse param to dict which is made from yaml.

We use easydict for this.

Refer to below code, then you would understand at a glance.


..


from easydict import EasyDict
import yaml

def load_setting(setting):
with open(setting, 'r') as f:
cfg = yaml.load(f, Loader=yaml.FullLoader)
return EasyDict(cfg)

#----------------------------
cfg = load_setting('test.yaml')
print(cfg)
#{'V1': 'abc', 'V2': {'sub': [1, 2, 3]}}
#----------------------------

#----------------------------
import argparse
paser = argparse.ArgumentParser()
args = paser.parse_args("")
args.batch_size=10
args.epoch=10
#----------------------------

cfg.update(vars(args))
print(cfg, type(cfg))
#{'V1': 'abc', 'V2': {'sub': [1, 2, 3]}, 'batch_size': 10, 'epoch': 10} <class 'easydict.EasyDict'>
#----------------------------

..


Thank you.

www.marearts.com


python yaml to dict

 refer to code

..

import yaml
with open('hparams.yaml', 'r') as stream:
try:
parsed_yaml=yaml.safe_load(stream)
print(parsed_yaml, type(parsed_yaml))
except yaml.YAMLError as exc:
print(exc)

..

> example output

{'batch_size': 1000, 'data_path': ['../npy/x_train_coin_eth.npy', '../npy/y_train_coin_eth.npy', '../npy/x_val_coin_eth.npy', '../npy/y_val_coin_eth.npy', '../npy/x_test_coin_eth.npy', '../npy/y_test_coin_eth.npy'], 'encoder_hidden_dims': [4, 2], 'input_dim': 5, 'input_seq': 128, 'learning_rate': 0.0001, 'num_LSTM': 2, 'num_layers': 1} <class 'dict'>


Thank you.
www.marearts.com


No module named 'yaml'

pip install pyyaml