Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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']"
like image 339
ChuckZ Avatar asked Sep 08 '26 10:09

ChuckZ


1 Answers

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'])
like image 55
unutbu Avatar answered Sep 11 '26 00:09

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!