argparse-dict 相互转换
argparse转dict
思路:在Python程序中定义好参数列表,然后从终端读取参数列表得到argparse对象,然后将该对象转化为dict对象。
import argparse
# define arguments
def parse_args(args=None):
parser = argparse.ArgumentParser()
parser.add_argument('--Name', type=str)
parser.add_argument('--ID', type=int)
parser.add_argument('--At_School', type=bool)
parser.add_argument('--Math_Score', type=float)
return parser.parse_args(args)
# program entrance
if __name__ == '__main__':
# read args from the terminal
an_args = parse_args()
# transfer the args to a dict
args_dict = vars(an_args)
print(args_dict)
# use the dict
for k in args_dict.keys():
print(k, args_dict[k], type(args_dict[k]))
输出如下
{'Name': None, 'ID': None, 'At_School': None, 'Math_Score': None}
Name None <class 'NoneType'>
ID None <class 'NoneType'>
At_School None <class 'NoneType'>
Math_Score None <class 'NoneType'>
dict转argparse
思路:调用argparse的静态方法Namespace,自动将dict的键值对转化为argparse对象
import argparse
# create a dict object
a_student = {'Name': 'JACK Williams',
'ID': 391568,
'At_School': True,
'Math_Score': 92.3}
# transfer the dict object to an ArgumentParser object
args = argparse.Namespace(**a_student)
print(args)
# use the ArgumentParser object
print(args.Name, type(args.Name))
print(args.ID, type(args.ID))
print(args.At_School, type(args.At_School))
print(args.Math_Score, type(args.Math_Score))
输出如下
JACK Williams <class 'str'>
391568 <class 'int'>
True <class 'bool'>
92.3 <class 'float'>