Python argparse dict arg

前端 未结 9 1684
不知归路
不知归路 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:50

    A straight forward way of parsing an input like:

    program.py --dict d --key key1 --value val1 --key key2 --value val2
    

    is:

    parser=argparse.ArgumentParser()
    parser.add_argument('--dict')
    parser.add_argument('--key', action='append')
    parser.add_argument('--value', action='append')
    args = parser.parse_args()
    

    which should produce (if my mental parser is correct)

    args = Namespace(dict='d', key=['key1','key2'], value=['value1','value2'])
    

    You should be able construct a dictionary from that with:

    adict = {k:v for k, v in zip(args.key, args.value)}
    

    Using args.dict to assign this to a variable with that name requires some un-python trickery. The best would be to create a element in another dictionary with this name.

    another_dict = {args.dict: adict}
    

    This solution doesn't perform much error checking. For example, it doesn't make sure that there are the same number of keys and values. It also wouldn't let you create multiple dictionaries (i.e. repeated --dict arguments). It doesn't require any special order. --dict could occur after a --key key1 pair. Several --value arguments could be together.

    Tying the key=value together as chepner does gets around a number of those problems.

提交回复
热议问题