gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:25:21 25 4
gpt4 key购买 nike

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

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)

但是得到了异常语法错误:关键字不能是表达式

最佳答案

使用:

success_response(**{the_key: the_value})

代替:

success_response(the_key=the_value)

关于python - 如何将变量值作为关键字参数键传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57932625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com