简体   繁体   English

递归地将 argparse 命名空间转换为字典

[英]Convert argparse Namespace to dict recursively

we already have some non-recursive solutions here .我们这里已经有了一些非递归的解决方案。

import argparse
args = argparse.Namespace()
args.foo = 1
args.bar = [1,2,3]
args.c = argparse.Namespace()
args.c.foo = 'a'

d = vars(args)


>>> d
{'foo': 1, 'bar': [1, 2, 3], 'c': Namespace(foo='a')}

The problem is if a second-level entry is also a Namespace, what we actually get is a dict of Namespace.问题是如果一个二级条目也是一个Namespace,我们实际得到的是一个Namespace的dict。

The question is if there is a handy recursive solution that is ready for us.问题是是否有为我们准备好的方便的递归解决方案。

I don't think there's an already-made recursive solution, but here's a simple one:我认为没有现成的递归解决方案,但这里有一个简单的解决方案:

def namespace_to_dict(namespace):
    return {
        k: namespace_to_dict(v) if isinstance(v, argparse.Namespace) else v
        for k, v in vars(namespace).items()
    }

>>> namespace_to_dict(args)
{'foo': 1, 'bar': [1, 2, 3], 'c': {'foo': 'a'}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM