I'd like to convert a OmegaConf/Hydra config to a nested dictionary/list. How can I do this?
Convert hydra/omegaconf config to python nested dict/list?
Does this answer your question? Converting a YAML file to Python JSON object –
Rosenstein
Usage snippet:
>>> conf = OmegaConf.create({"foo": "bar", "foo2": "${foo}"})
>>> assert type(conf) == DictConfig
>>> primitive = OmegaConf.to_container(conf)
>>> show(primitive)
type: dict, value: {'foo': 'bar', 'foo2': '${foo}'}
>>> resolved = OmegaConf.to_container(conf, resolve=True)
>>> show(resolved)
type: dict, value: {'foo': 'bar', 'foo2': 'bar'}
Snippet:
from omegaconf import OmegaConf; OmegaConf.to_container(cfg)
–
Jhelum Added usage snippet to answer. –
Delouse
wonder why resolve=True is not the default. –
Jessiajessica
resolving interpolations is a destructive operation that is changing the semantics of the config. e.g. modifying foo in the original config will change both foo and foo2 but it does not hold the same way after you resolve. –
Delouse
what is
show
? –
Bailsman A one-liner to print the object and the type. defined in the linked doc page. –
Delouse
One can simply convert from omegaconf to python dictionary by dict(). Follow the example given below:
>>> type(config)
<class 'omegaconf.dictconfig.DictConfig'>
>>> config
{'host': '0.0.0.0', 'port': 8000, 'app': 'main:app', 'reload': False, 'debug': False}
>>> dict(config)
{'host': '0.0.0.0', 'port': 8000, 'app': 'main:app', 'reload': False, 'debug': False}
>>> type(dict(config))
<class 'dict'>
This does not convert nested DictConfig objects inside the top-level object –
Littman
© 2022 - 2024 — McMap. All rights reserved.