Give dictionary type options with python-argparse

problem

I want to enter multiple values with command line options, but I want to enter them as a named dictionary instead of list format

In other words

hoge.py --param a=foo --param b=param when bar= {"a": "foo", "b": "bar"]I want to take out the argument.



# solution
 Define the original argparse.Action. You can create a class that inherits Action and override the __call__ method.

 Since the raw string is included in values, you can add it appropriately to namespace, but in this problem namespace.param may already exist, so check it .. By the way, the character string "param" is included in self.dest.

```py
import argparse
class ParamProcessor(argparse.Action):
    """
    --param foo=argparse to put a type argument into dictionary.Action
    """
    def __call__(self, parser, namespace, values, option_strings=None):
        param_dict = getattr(namespace,self.dest,[])
        if param_dict is None:
            param_dict = {}

        k, v = values.split("=")
        param_dict[k] = v
        setattr(namespace, self.dest, param_dict)

Try using

parser=argparse.ArgumentParser()
parser.add_argument("--param", action=ParamProcessor)

args = parser.parse_args()
print(args.param)
$ python hoge.py --param foo=a --param bar=b
>>> {'foo': 'a', 'bar': 'b'}

Recommended Posts

Give dictionary type options with python-argparse
Dictionary type 2
Dictionary type 1
Dictionary type Key Error countermeasures
Simple synonym dictionary with sudachipy