4

Currently I need to implement a python program that takes an arbitrary number of commandline arguments like

python myprog.py x1=12 y3=hello zz=60

and the arguments need to be converted into a dictionary like

{"x1": "12", "y3": "hello", "zz": "60"}

I tried the argparse module, but the keys in the arguments (x1, y3, zz in the example) cannot be known beforehand, while argparse seems to need me to add the argument keys individually, so I don't think it fits this specific situation?

Any idea how to accomplish this kind of commandline args to dictionary conversion, have I missed something about argparse or do I need to use something else?

hellopeach
  • 924
  • 8
  • 15

1 Answers1

3

You can just parse it by processing the strings. e.g.

import sys

kw_dict = {}
for arg in sys.argv[1:]:
    if '=' in arg:
        sep = arg.find('=')
        key, value = arg[:sep], arg[sep + 1:]
        kw_dict[key] = value
Kevin He
  • 1,210
  • 8
  • 19
  • Should probably do `for arg in sys.argv[1:]:`, since the program name should never be a useful argument. Also, using `key, sep, value = arg.partition('=')` will allow the value to contain an equals sign without causing an exception. – ShadowRanger Jan 08 '19 at 18:24
  • noted. I guess the main problem with my old code was that it cannot handle more than one equal signs. updated code. – Kevin He Jan 08 '19 at 18:27