Handling undefined pair arguments with argparse

In my project , I need to define a syntax like

mcraw recipe add COUNT ID COUNT_1 ID_1 [COUNT_2 ID_2 ..] 

and argparse seems like the best tool for general work.

How can I instruct Python and its argparse to build such a dictionary?

 { ID_1: COUNT_1, ID_2: COUNT_2, ... } 
+1
source share
2 answers

Read your arguments in pairs:

 argdict = {args[i + 1]: args[i] for i in xrange(0, len(args), 2)} 

argparse has no special handling for such input.

+2
source

I think you may have the wrong approach. Why not point to a .json file for your program to accept it on the command line?

In this way

 $> python mcraw recipe add --recipies=my_recipies.json 

And you can pull it and use as you like, features include, for example, what Martijn answers

0
source

All Articles