Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a variable value as keyword argument key?

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

like image 701
wulfnb Avatar asked Jan 26 '23 20:01

wulfnb


1 Answers

Use:

success_response(**{the_key: the_value})

Instead of:

success_response(the_key=the_value)
like image 79
Dipen Dadhaniya Avatar answered Jan 31 '23 22:01

Dipen Dadhaniya