I want to receive a dict(str -> str)
argument from the command line. Does argparse.ArgumentParser
provide it? Or any other library?
For the
A straight forward way of parsing an input like:
program.py --dict d --key key1 --value val1 --key key2 --value val2
is:
parser=argparse.ArgumentParser()
parser.add_argument('--dict')
parser.add_argument('--key', action='append')
parser.add_argument('--value', action='append')
args = parser.parse_args()
which should produce (if my mental parser is correct)
args = Namespace(dict='d', key=['key1','key2'], value=['value1','value2'])
You should be able construct a dictionary from that with:
adict = {k:v for k, v in zip(args.key, args.value)}
Using args.dict
to assign this to a variable with that name requires some un-python trickery. The best would be to create a element in another dictionary with this name.
another_dict = {args.dict: adict}
This solution doesn't perform much error checking. For example, it doesn't make sure that there are the same number of keys and values. It also wouldn't let you create multiple dictionaries (i.e. repeated --dict
arguments). It doesn't require any special order. --dict
could occur after a --key key1
pair. Several --value
arguments could be together.
Tying the key=value
together as chepner
does gets around a number of those problems.
use vars
d = vars(parser.parse_args())
Python one-line argparse dictionary arguments argparse_dictionary.py
# $ python argparse_dictionary.py --arg_dict=1=11,2=22;3=33 --arg_dict=a=,b,c=cc,=dd,=ee=,
# Namespace(arg_dict={'1': '11', '2': '22', '3': '33', 'a': '', 'c': 'cc', '': 'dd'})
import argparse
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument(
'--arg_dict',
action=type(
'', (argparse.Action, ),
dict(__call__=lambda self, parser, namespace, values, option_string: getattr(
namespace, self.dest).update(
dict([
v.split('=') for v in values.replace(';', ',').split(',')
if len(v.split('=')) == 2
])))),
default={},
metavar='KEY1=VAL1,KEY2=VAL2;KEY3=VAL3...',
)
print(arg_parser.parse_args())