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']"
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'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With