Python 使用 ArgumentParser 将 List[str] 转换为 Dict[str, str]
我需要解析命令行参数 - 将 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
type
参数应用于--model-config
之后的每个输入之前它们被附加到存储在解析的列表中参数作为属性.model_config
。换句话说,model_config
的值将是List[model_config_str_to_dict(mc_arg)]
,而不是model_config_str_to_dict(List[mc_arg])
作为示例:
如果您想将其转换为字典,您可以在解析参数之后执行此操作。
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 ofmodel_config
will beList[model_config_str_to_dict(mc_arg)]
, notmodel_config_str_to_dict(List[mc_arg])
As an example:
If you want to convert this to a dictionary, you can do that after parsing the arguments.