3

Assume that I am expecting a list of lists where the inner lists have different types and lengths, e. g.,

[[1, 2], ["foo", "bar"], [3.14, "baz", 20]]

how can I parse the above list using argparse?

Most useful questions on stackoverflow:

Similar questions exist, where most useful one is here. But they are not good enough in my case as they ignore the fact that the list is nested with different data types and lenghts.

Meysam Sadeghi
  • 1,483
  • 2
  • 17
  • 23
  • 2
    why not just do https://stackoverflow.com/a/24866869/1358308 but use `json.loads` for the `type` parameter? – Sam Mason Jul 19 '19 at 12:36
  • This is what I am doing at the moment. The problem is that then you are required to parse the string, in my example "[[1, 2], ['foo', 'bar'], [3.14, 'baz', 20]]", and extract the data. Hence, I was wondering if there is a more efficient way? Could you comment how the `type` can be handled with `json.loads`? – Meysam Sadeghi Jul 19 '19 at 12:53
  • 1
    note that using `json` implies that strings are in double quotes, whereas your example has single quotes. any reason for this? – Sam Mason Jul 19 '19 at 12:56
  • No, I revised that. – Meysam Sadeghi Jul 19 '19 at 13:05

1 Answers1

3

expanding on my comment:

from argparse import ArgumentParser
import json

parser = ArgumentParser()
parser.add_argument('-l', type=json.loads)
parser.parse_args(['-l', '[[1,2],["foo","bar"],[3.14,"baz",20]]'])

prints:

Namespace(l=[[1, 2], ['foo', 'bar'], [3.14, 'baz', 20]])
Sam Mason
  • 15,216
  • 1
  • 41
  • 60