Multiple grouping using argparser in python

Viewed 53

Hi I want to group vars in the way I pass in command line. Consider following example.

shell> python cli.py -a 1 -b 23 -b 3 -a 2 -b 7

So the grouping should happen as all b's before 2nd 'a' should belong to first 'a' and last 'b' belongs to last 'a'

So final result after parse output should be

first a {value:1,b:[23,3]}
Second a {value:2,b:[7]}

I tried multiple ways of using argparse to build it, but could not find logic to do it.

1 Answers

I had a similar problem and i solved it by using two arrays for a's and b's. In python lists are great, since you can store lists of lists easily. When the parser encounters variable a,

The big list looks like

[[a1]], when b1 and b2 are encountered,

[[a1, b1, b2]], a2 encountered,

[[a1, b1, b2], [a2]], and so on and so forth.

Do you like this solution?

Related