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.

asked Jul 19, 2019 at 12:34
4
  • 2
    why not just do stackoverflow.com/a/24866869/1358308 but use json.loads for the type parameter? Commented Jul 19, 2019 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? Commented Jul 19, 2019 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? Commented Jul 19, 2019 at 12:56
  • No, I revised that. Commented Jul 19, 2019 at 13:05

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

And you might need escaping the quotes when actually calling your program from bash

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.