ChuckZ
ChuckZ

Reputation: 340

Python argparse passing list or dictionary via command line

I have seen questions about passing in dictionaries and lists to Python using the argparse library. The examples all show what my Python code looks like. But none show me what they look like on the command line. Where do I need braces, brackets, and quotes?

So if I wanted parameters --my_dict and --my_list how would I specify them as called from the command line?

Here is the essence of what I want to accomplish:

Python foo.py --my_dict="{'Name': 'Zara', 'Class': 'First'}" --my_list="['a', 'b', 'c']"

Upvotes: 3

Views: 5778

Answers (1)

unutbu
unutbu

Reputation: 879083

You could use ast.literal_eval to safely convert user-inputted strings to Python dicts and lists:

import argparse
import ast
parser = argparse.ArgumentParser()
parser.add_argument('--my_dict', type=ast.literal_eval)
parser.add_argument('--my_list', type=ast.literal_eval)
args = parser.parse_args()
print(args)

Running

% python script.py --my_dict="{'Name': 'Zara', 'Class': 'First'}" --my_list="['a', 'b', 'c']"

yields

Namespace(my_dict={'Name': 'Zara', 'Class': 'First'}, my_list=['a', 'b', 'c'])

Upvotes: 8

Related Questions