Python argparse dict arg [英] 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屋!