I need to pass the value of a variable as a key of keyword agument.
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)
actual output is
{'status': 'success', 'message': 'Success Msg', 'the_key': [{'id': 1, 'name': 'Product1'}, {'id': 2, 'name': 'Product2'}]}
expected output is
{'status': 'success', 'message': 'Success Msg', 'purchase': [{'id': 1, 'name': 'Product1'}, {'id': 2, 'name': 'Product2'}]}
I tried eval()
success_response(eval(the_key)=the_value)
but got the exception
SyntaxError: keyword can't be an expression
Use:
success_response(**{the_key: the_value})
Instead of:
success_response(the_key=the_value)
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