我需要将变量的值作为关键字参数的键传递。

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)

但得到了例外 SyntaxError: keyword can't be an expression

分析解答

采用:

success_response(**{the_key: the_value})

代替:

success_response(the_key=the_value)