How to pass a variable value as keyword argument key?

wulfnb

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

Dipen Dadhaniya

Use:

success_response(**{the_key: the_value})

Instead of:

success_response(the_key=the_value)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to pass variable object as a value argument

How to pass a dict as a positional argument, not a keyword argument

How to pass `lambda: pass` as keyword argument?

How to pass variable key value in dynamodb

How to pass a variable as an argument

Pass Variable Value as Argument to Command

How to pass None keyword as command line argument

How to pass the string with whitespace as a keyword argument

how to pass string into a method as a keyword argument

How to pass a tensor type value to the shape argument of Variable?

How to pass only the value of controller variable as argument in Ionic

How to pass the value of a variable to an argument of a function in Macro SAS?

how to pass local variable and argument of same name (using this keyword )inside lambda functions in c++?

how to give object to keyword argument as key

Pass Python keyword as an argument?

How to pass an argument with no value to CMake?

Is there a way to pass variable itself(not the value) as argument in Python?

how to pass whole keyword into for loop variable | linux |

How to pass a variable as an argument to a function if the variable exists

How to pass a function argument as a key in a dictionary in Python

How do you pass parameters to a function passed as a keyword argument?

How to pass array of element as argument in includes keyword in reactjs or js

How to use the value of a variable as an argument

How to pass a key field as variable instead of hard-coded key value to OData operation?

how to pass mutually exclusive argument as a variable

How to pass argument to ENTRYPOINT with variable expansion?

Python: how to pass argument name using variable

How to pass variable argument in meteor find method

how to pass string variable as globbing argument to command