How to pass dictionary as command line argument to Python script?

The important thing to note here is that at the command line you cannot pass in python objects as arguments. The current shell you are using will parse the arguments and pass them in according to it’s own argument parsing rules.

That being said, you cannot pass in a python dictionary. However, things like JSON can allow you to get pretty darn close.

JSON – or JavaScript Object Representation is a way of taking Python objects and converting them into a string-like representation, suitable for passing around to multiple languages. That being said, you could pass in a string like this:

python saver.py '{"names": ["J.J.", "April"], "years": [25, 29]}'

In your python script, do this:

import json
data=json.loads(argv[1])

This will give you back a dictionary representing the data you wanted to pass in.

Likewise, you can take a python dictionary and convert it to a string:

import json
data={'names': ["J.J.", "April"], 'years': [25,29]}
data_str=json.dumps(data)

There are other methods of accomplishing this as well, though JSON is fairly universal. The key thing to note is that regardless of how you do it – you won’t be passing the dictionary into Python, – you’ll be passing in a set of arguments (which will all be strings) that you’ll need to somehow convert into the python type you need.

@EvanZamir – note that (generally) in a shell, you need to escape quotes if they appear in your quoted string. In my example, I quote the JSON data with single quotes, and the json string itself uses double quotes, thereby obviating the need for quotes.

If you mix quotes (use double quotes to quote the argument, and double quotes inside), then the shell will require it to be escaped, otherwise the first double quote it encounters is considered the “closing quote” for the argument. Note in the example, I use single quotes to enclose the JSON string, and double quotes within the string. If I used single quotes in the string, I would need to escape them using a backslash, i.e.:

python saver.py '{"names": ["J.J.", "April\'s"], "years": [25, 29]}'

or

python saver.py "{\"names\": [\"J.J.\", \"April's\"], \"years\": [25, 29]}"

Note the quoting stuff is a function of your shell, so YMMV might vary (for example, if you use some exec method to call the script, escaping might not be required since the bash shell might not be invoked.)

Leave a Comment