我需要将变量的值作为关键字参数的键传递。
def success_response(msg=None,**kwargs):
output = {"status": 'success',
"message": msg if msg else 'Success Msg'}
for key,value in kwargs.items():
output.update({key:value})
return output
the_key = 'purchase'
the_value = [
{"id": 1,"name":"Product1"},
{"id": 2,"name":"Product2"}
]
success_response(the_key=the_value)
实际输出为
{'status': 'success', 'message': 'Success Msg', 'the_key': [{'id': 1, 'name': 'Product1'}, {'id': 2, 'name': 'Product2'}]}
预期输出是
{'status': 'success', 'message': 'Success Msg', 'purchase': [{'id': 1, 'name': 'Product1'}, {'id': 2, 'name': 'Product2'}]}
我试过 eval()
success_response(eval(the_key)=the_value)
但是得到了异常语法错误:关键字不能是表达式
使用:
success_response(**{the_key: the_value})
代替:
success_response(the_key=the_value)
我是一名优秀的程序员,十分优秀!