yacs icon indicating copy to clipboard operation
yacs copied to clipboard

[Feature Request] Convert to dict

Open re-young opened this issue 5 years ago • 4 comments

Hey,

It would be great to have the native ablilty to convert config into a dict.

https://github.com/rbgirshick/yacs/blob/8a679b445174e4c284858732b485a5a2fa678058/yacs/config.py#L191

re-young avatar Apr 17 '19 21:04 re-young

A follow up to this question, can we use CfgNode like dict? i.e. cfg['key'] can return the value of the key.

DKandrew avatar May 28 '20 04:05 DKandrew

Here is my implementation (copied from the config.py)

_VALID_TYPES = {tuple, list, str, int, float, bool}


def convert_to_dict(cfg_node, key_list=[]):
    """ Convert a config node to dictionary """
    if not isinstance(cfg_node, CfgNode):
        if type(cfg_node) not in _VALID_TYPES:
            print("Key {} with value {} is not a valid type; valid types: {}".format(
                ".".join(key_list), type(cfg_node), _VALID_TYPES), )
        return cfg_node
    else:
        cfg_dict = dict(cfg_node)
        for k, v in cfg_dict.items():
            cfg_dict[k] = convert_to_dict(v, key_list + [k])
        return cfg_dict

DKandrew avatar May 31 '20 04:05 DKandrew

For non-nested cfgNodes you can cast it into dict -> (dict)(your_cfgNode). Otherwise you need to do it recursively.

tekinengin avatar Apr 18 '22 16:04 tekinengin