1

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,
  ...
}
Sean Allred
  • 3,558
  • 3
  • 32
  • 71
  • Can you modify the syntax slightly to `mcraw recipe add COUNT ID COUNT_1,ID1 COUNT_2,ID2 ...`? This would make writing a custom action which processes each comma-delimted pair and adds the corresponding dictionary much easier. – chepner Jun 15 '13 at 17:31

2 Answers2

3

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Same answer, but different syntax: `argdict = {arg1: arg2 for (arg1, arg2) in zip(*[iter(args)]*2)}` as seen here: https://stackoverflow.com/a/5389547/778533 – tommy.carstensen Jul 28 '17 at 21:52
  • @tommy.carstensen: sure, but in Python 2 `zip()` produces a list, not an iterator, which is why that answer uses `itertools.izip()` instead. There is more than one way to solve the pairwise iteration problem. – Martijn Pieters Jul 28 '17 at 21:55
  • 1
    @tommy.carstensen: but once you use `zip()` / `izip()`, just use `dict()` and not a dict comprehenion: `a = iter(args); argdict = dict(izip(a, a))` – Martijn Pieters Jul 28 '17 at 21:56
0

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

Community
  • 1
  • 1
yurisich
  • 6,991
  • 7
  • 42
  • 63
  • Can you expand on why JSON would be a better format? I'm more than open to suggestions as to how this should work; I haven't actually designed the database yet. Would you edit in a potential format for the JSON file? – Sean Allred Jun 15 '13 at 18:49
  • I feel it's simpler to create the data for the application before hand, but if that's not possible, creating a dictionary and using `json.dumps` is easy too. Modifying individual entries is a piece of cake as well. Do you want me to continue? – yurisich Jun 15 '13 at 19:12