Convert hydra/omegaconf config to python nested dict/list?
Asked Answered
R

2

20

I'd like to convert a OmegaConf/Hydra config to a nested dictionary/list. How can I do this?

Really answered 12/10, 2021 at 20:9 Comment(1)
Does this answer your question? Converting a YAML file to Python JSON objectRosenstein
D
34

See OmegaConf.to_container().

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'}
Delouse answered 12/10, 2021 at 21:26 Comment(6)
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
H
5

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'>
Historiography answered 14/7, 2023 at 6:42 Comment(1)
This does not convert nested DictConfig objects inside the top-level objectLittman

© 2022 - 2024 — McMap. All rights reserved.