繁体   English   中英

如何将变量值作为关键字参数键传递?

[英]How to pass a variable value as keyword argument key?

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

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)

这行的key

for key,value in kwargs.items():

是关键字参数的名称。 在这种情况下, key将是the_key ,这意味着传递给output.update(value)的字典value将是

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

我认为您真正想要的是:

success_response(purchase=the_value)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM