Python argparse dict arg [英] Python argparse dict arg

查看:488
本文介绍了Python argparse dict arg的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从命令行接收一个 dict(str - > str)参数。提供 argparse.ArgumentParser 或任何其他图书馆?

I want to receive a dict(str -> str) argument from the command line. Does argparse.ArgumentParser provide it? Or any other library?

对于命令行:

program.py --dict d --key key1 --value val1 --key key2 --value val2

我希望以下字典:

d = {"key1": "val1", "key2": "val2"}


推荐答案

我会使用这样的东西:

p = argparse.ArgumentParser()
p.add_argument("--keyvalue", action='append',
               type=lambda kv: kv.split("="), dest='keyvalues')

args = p.parse_args("--keyvalue foo=6 --keyvalue bar=baz".split())
d = dict(args.keyvalues)

您可以创建自定义操作这将把一个解析的键值对附加到字典中,而不是简单地累积一个(key,value)元组的列表。 (我看到的是sky75489做什么;我的回答与使用单个 - keyvalue 选项与自定义类型而不是单独的 - 键 - 值选项来指定对。)

You could create a custom action which would "append" a parsed key-value pair directly into a dictionary, rather than simply accumulating a list of (key, value) tuples. (Which I see is what skyline75489 did; my answer differs in using a single --keyvalue option with a custom type instead of separate --key and --value options to specify pairs.)

这篇关于Python argparse dict arg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆