wulfnb
wulfnb

Reputation: 111

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

Upvotes: 5

Views: 2485

Answers (2)

Dipen Dadhaniya
Dipen Dadhaniya

Reputation: 4630

Use:

success_response(**{the_key: the_value})

Instead of:

success_response(the_key=the_value)

Upvotes: 10

kingkupps
kingkupps

Reputation: 3504

The key in this line:

for key,value in kwargs.items():

is the name of the keyword argument. In this case, key will be the_key which means the dictionary value passed to output.update(value) will be

[
    {"id": 1,"name":"Product1"},
    {"id": 2,"name":"Product2"}
]

I think what you really want is:

success_response(purchase=the_value)

Upvotes: 0

Related Questions