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>The question of handling arbitrary key/value pairs has come up a number of times.  <code>argparse</code> does not have a builtin mechanism for that.</p>

<p><a href="http://stackoverflow.com/questions/37367331/argparse-arbitrary-optional-arguments">argparse - Arbitrary optional arguments</a>  (almost a duplicate from last May)</p>

<p>Your idea of using <code>parse_know_args</code> and then doing your own dictionary build from the <code>extras</code> is good - and perhaps the simplest.  How you handle the extras list will depend on how well behaved your users are (predicable <code>'--key', 'value'</code> pairs).  This basically the same as if you parsed <code>sys.arv[1:]</code> directly.</p>

<p>If the user gives input like <code>--options key1:value1 key2=value2 "key3 value3"</code> you can parse those pairs in a custom Action class (e.g. split the string on the delimiter etc).</p>

<p>Input like <code>--options "{key1: value1, key2: value2}"</code> can be handled as a <code>JSON</code> string, with a type function like: <code>type=json.load</code> (I'd have to look that up).</p>

python argparse