Python parse_known_args with named arguments
<p>I would like to pass an arbitrary set of arguments in the format <code>--arg1 value1</code> to my python script and retrieve them in a dictionary of the kind <code>{'arg1': 'value1}</code>. I want to use <code>argparse</code> to achieve that. The function <code>parse_known_args</code> allows for extra args, but they can be retrieved as a simple list and are not named.</p>

<p>A better idea is to define <em>one</em> option that takes two arguments, a name and a value, and use a custom action to update a dictionary using those two arguments.</p>

<pre><code>class OptionAppend(Action):
    def __call__(self, parser, namespace, values, option_string):
        d = getattr(namespace, self.dest)
        name, value = values
        d[name] = value

p.add_argument("-o", "--option", nargs=2, action=OptionAppend, default={})
</code></pre>

<p>Then instead of <code>myscript --arg1 value1 --arg2 value2</code>, you would write <code>myscript -o arg1 value1 -o arg2value1</code>, and after <code>args = parser.parse_args()</code>, you would have <code>args.o == {'arg1': 'value1, 'arg2': 'value2'}</code>.</p>

<hr>

<p>This is somewhat analogous to the use of a list or dictionary to hold a set of related variables, instead of a set of individually named variables.</p>

<pre><code> # Good
 v = [x, y, z]
 v = { 'key1': x, 'key2': y, 'key3': z}
 # Bad
 v1 = x
 v2 = y
 v3 = z
</code></pre>

python argparse