'How to get nested dict from argument_group

I wanted different part of the program to see only the necessary args parsed.

parser = argparse.ArgumentParser()
log = parser.add_argument_group()
log.add_argument('--name')

mp = parser.add_argument_group()
mp.add_argument('--processes', type=int)

args = parser.parse_args()

I'm hoping for a dict like {'mp':{'processes'=1}, 'log':{'name'='log.log'}}, but vars(args) flatten this to {'processes'=1, 'name'='log.log'}



Solution 1:[1]

Although this is not a precise solution to the question, it returns the ideal dict.

class Config(Namespace):
    def __setattr__(self, name, value):
        if '.' in name:
            name = name.split('.')
            name, rest = name[0], '.'.join(name[1:])
            setattr(self, name, type(self)())
            setattr(getattr(self, name), rest, value)
        else:
            super().__setattr__(name, value)

    def dict(self):
        dict = {}
        for k, v in self.__dict__.items():
            if isinstance(v, Config):
                dict[k] = v.dict()
            else:
                dict[k] = v
        return dict

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 Zhiyuan Chen