Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse a nested list with python argparse

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.

like image 731
Meysam Sadeghi Avatar asked Dec 01 '25 02:12

Meysam Sadeghi


1 Answers

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]])
like image 193
Sam Mason Avatar answered Dec 06 '25 03:12

Sam Mason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!