'OmegaConf: convert dict into List of Objects
I am trying to automatically convert
from omegaconf import OmegaConf
s = """
nodes:
node1:
group: standard
status: online
node2:
group: small
status: online
node3:
group: standard
status: offline
"""
into a list of nodes, where "node1/2/3" is the name of the node:
from dataclasses import dataclass
from typing import List
@dataclass
class Node:
name: str
group: str
status: str
@dataclass
class Config:
nodes: List[Node]
with
conf = OmegaConf.create(s)
schema = OmegaConf.structured(Config)
merged_conf = OmegaConf.merge(schema, conf)
Is there a mechanism in place for this? If I try it out-of-the-box I get
omegaconf.errors.ConfigTypeError: Cannot merge DictConfig with ListConfig
Solution 1:[1]
The error is telling you that you are attempting to merge a dictionary with a List, which is not supported.
Your schema says that nodes is a List[Node], but your YAML string contains a mapping (YAML terminology for a dictionary).
Either change your schema to indicate that nodes is a Dict:
@dataclass
class Config:
nodes: Dict[str, Node]
Or change your YAML string to contain a list:
s = """
nodes:
- group: standard
status: online
- group: small
status: online
- group: standard
status: offline
"""
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Omry Yadan |
