Python 使用 ArgumentParser 将 List[str] 转换为 Dict[str, str]

发布于 2025-01-10 15:19:03 字数 527 浏览 4 评论 0原文

我需要解析命令行参数 - 将 List[str] 转换为 Dict[str, str]

['key1=value1', 'key2=value2'] -> {key1: value1, key2:value2}

我使用以下代码:

 parser.add_argument(
        '--model-config',
        nargs='+',
        type=model_config_str_to_dict        
    )

其中 model_config_str_to_dict(model_config: List[ str]) 是将列表转换为字典的函数。但我得到的是 model_config 参数的 str 而不是 List[str]

我的问题是如何解析 --model-config 参数以将其转换为字典?

I need to parse command line argument - convert List[str] to Dict[str, str]

['key1=value1', 'key2=value2'] -> {key1: value1, key2:value2}

I use the following code:

 parser.add_argument(
        '--model-config',
        nargs='+',
        type=model_config_str_to_dict        
    )

where model_config_str_to_dict(model_config: List[str]) is a function to convert list to dict. But instead of List[str] I get str for the model_config parameter.

My question is how can I parse --model-config parameter to convert it to dict?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

葬花如无物 2025-01-17 15:19:03

type 参数应用于 --model-config 之后的每个输入之前它们被附加到存储在解析的列表中参数作为属性 .model_config。换句话说,model_config 的值将是 List[model_config_str_to_dict(mc_arg)],而不是 model_config_str_to_dict(List[mc_arg])

作为示例:

import argparse

def model_config_split(s):
    k, v = s.split('=', 1)
    return (k, v)

parser = argparse.ArgumentParser()
parser.add_argument( '--model-config',
        nargs='+',
        type=model_config_str_to_dict)

args = parser.parse_args(['--model-config', 'key1=value1', 'key2=value2'])
print(args.model_config)

# prints:
# [('key1', 'value1'), ('key2', 'value2')]

如果您想将其转换为字典,您可以解析参数之后执行此操作。

args.model_config = dict(args.model_config)
print(args.model_config)

# prints:
# {'key1': 'value1', 'key2': 'value2'}

The type argument is applied to each of the inputs following --model-config before they are appended to a list that is stored in the parsed arguments as the attribute .model_config. In other words, the value of model_config will be List[model_config_str_to_dict(mc_arg)], not model_config_str_to_dict(List[mc_arg])

As an example:

import argparse

def model_config_split(s):
    k, v = s.split('=', 1)
    return (k, v)

parser = argparse.ArgumentParser()
parser.add_argument( '--model-config',
        nargs='+',
        type=model_config_str_to_dict)

args = parser.parse_args(['--model-config', 'key1=value1', 'key2=value2'])
print(args.model_config)

# prints:
# [('key1', 'value1'), ('key2', 'value2')]

If you want to convert this to a dictionary, you can do that after parsing the arguments.

args.model_config = dict(args.model_config)
print(args.model_config)

# prints:
# {'key1': 'value1', 'key2': 'value2'}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文