Search code examples
python-3.xcommand-line-argumentsargs

How to convert commandline "key=value" args to dictionary?


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?


Solution

  • 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