Python argparse dict arg

前端 未结 9 1683
不知归路
不知归路 2021-02-01 04:31

I want to receive a dict(str -> str) argument from the command line. Does argparse.ArgumentParser provide it? Or any other library?

For the

9条回答
  •  被撕碎了的回忆
    2021-02-01 04:49

    Python receives arguments in the form of an array argv. You can use this to create the dictionary in the program itself.

    import sys
    my_dict = {}
    for arg in sys.argv[1:]:
        key, val=arg.split(':')[0], arg.split(':')[1]
        my_dict[key]=val
    
    print my_dict
    

    For command line:

    python program.py key1:val1 key2:val2 key3:val3
    

    Output:

    my_dict = {'key3': 'val3', 'key2': 'val2', 'key1': 'val1'}
    

    Note: args will be in string, so you will have to convert them to store numeric values.

    I hope it helps.

提交回复
热议问题