Sean Allred
Sean Allred

Reputation: 3658

Handling indefinite paired 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 to be the best tool for the general job.

How can I instruct Python and its argparse to construct a dictionary like this?

{
  ID_1: COUNT_1,
  ID_2: COUNT_2,
  ...
}

Upvotes: 1

Views: 557

Answers (2)

yurisich
yurisich

Reputation: 7119

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

That way

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

And you can pull it in and use it however you like, possibilities include such as what is in Martijn's answer

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1124558

Read your arguments in pairs:

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

argparse has otherwise no special handling for this kind of input.

Upvotes: 3

Related Questions