0

I want to pass a dictionary on command line. The following code fails:

import json
import argparse

parser = argparse.ArgumentParser(description='Test Arg Parse')
parser.add_argument('-d', '--dict', type=dict, required=False)

variables = vars(parser.parse_args())
print json.dumps(variables)

When I'm running the program, it throws the following error:

C:\KTLO\bin>python TestProg.py -d "{'a':'b'}"
usage: TestProg.py [-h] [-d DICT]
TestProg.py: error: argument -d/--dict: invalid dict value: "{'a':'b'}"

Edit 1: Specifying 'json.loads' or 'dict' does not change the output and still it throws the error.

Nitin Pandey
  • 649
  • 1
  • 9
  • 27

1 Answers1

1

Try

python TestProg.py -d '{"a":"b"}'

single quotes are no valid json.

allo
  • 3,955
  • 8
  • 40
  • 71
  • `C:\KTLO\bin>python TestProg.py -d '{"a":"b"}' usage: TestProg.py [-h] [-d DICT] TestProg.py: error: argument -d/--dict: invalid dict value: "'{a:b}'" ` Doesn't work – Nitin Pandey Jul 07 '16 at 10:16
  • 1
    i guess additional your ``default=`` should be ``type=``, see http://stackoverflow.com/a/18609361/893159 – allo Jul 07 '16 at 10:17
  • @psychoCoder note that you're quoting the whole object, not the keys and values in it. – jonrsharpe Jul 07 '16 at 11:14