Home > Mobile >  Argparse: modify default values based on dictionary
Argparse: modify default values based on dictionary

Time:07-30

I have defined a parser, let's say:

parser = argparse.ArgumentParser(description='My Parser')
parser.add_argument("--Arg0", type=str, default="str")
parser.add_argument('--Arg1', type=int, default=0)

Now I have a dict containing the same arguments/keys:

parameters = {'Arg0': "NewStr", 'Arg1': 0}

I want to replace the default values in my parser by the ones in the dict. I tried to iterate through the dict keys and do parser.set_default(key=parameters[key]) but it just adds the new argument key with the value parameters[key]

So, how can I modify the parser default value for Arg0 and Arg1 based on the information contained in the dict?

CodePudding user response:

You can use ArgumentParser.set_defaults like this:

parser.set_defaults(**parameters)
  • Related