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.
asked Jul 19, 2019 at 12:34
Meysam Sadeghi
1,6732 gold badges20 silver badges25 bronze badges
1 Answer 1
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]])
answered Jul 19, 2019 at 12:54
Sam Mason
16.5k1 gold badge49 silver badges71 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
matanox
And you might need escaping the quotes when actually calling your program from bash
lang-py
json.loadsfor thetypeparameter?typecan be handled withjson.loads?jsonimplies that strings are in double quotes, whereas your example has single quotes. any reason for this?