Python argparse dict arg

前端 未结 9 1774
不知归路
不知归路 2021-02-01 04:31

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

For the

9条回答
  •  自闭症患者
    2021-02-01 04:41

    I would use something like this:

    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)
    

    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.)

提交回复
热议问题