Python convert List[str] to Dict[str, str] using ArgumentParser

Viewed 74

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?

1 Answers

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 of model_config will be List[model_config_str_to_dict(mc_arg)], not model_config_str_to_dict(List[mc_arg])

As an example:

import argparse

def model_config_split(s):
    k, v = s.split('=', 1)
    return (k, v)

parser = argparse.ArgumentParser()
parser.add_argument( '--model-config',
        nargs='+',
        type=model_config_str_to_dict)

args = parser.parse_args(['--model-config', 'key1=value1', 'key2=value2'])
print(args.model_config)

# prints:
# [('key1', 'value1'), ('key2', 'value2')]

If you want to convert this to a dictionary, you can do that after parsing the arguments.

args.model_config = dict(args.model_config)
print(args.model_config)

# prints:
# {'key1': 'value1', 'key2': 'value2'}
Related