使用变量作为关键字传递给Python中的** kwargs [英] Using variable as keyword passed to **kwargs in Python

查看:153
本文介绍了使用变量作为关键字传递给Python中的** kwargs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过API更新记录的功能.该API接受各种可选的关键字参数:

I have a function that updates a record via an API. The API accepts a variety of optional keyword parameters:

def update_by_email(self, email=None, **kwargs):
    result = post(path='/do/update/email/{email}'.format(email=email), params=kwargs)

我还有另一个函数,该函数使用第一个函数来更新记录中的单个字段:

I have another function that uses the first function to update an individual field in the record:

def update_field(email=None, field=None, field_value=None):
    """Encoded parameter should be formatted as <field>=<field_value>"""
    request = update_by_email(email=email, field=field_value)

这不起作用.当我打电话时:

This doesn't work. When I call:

update_field(email='joe@me.com', field='name', field_value='joe')

URL编码为:

https://www.example.com/api/do/update/email/joe@me.com?field=Joe

如何将其编码为:

https://www.example.com/api/do/update/email/joe@me.com?name=Joe

谢谢.

推荐答案

除了传递名为field的参数外,您还可以使用字典解包将 field值用作参数名称:

Rather than passing the parameter named as field, you can use dictionary unpacking to use the value of field as the name of the parameter:

request = update_by_email(email, **{field: field_value})

使用update_by_email的模拟:

def update_by_email(email=None, **kwargs):
    print(kwargs)

当我打电话

update_field("joe@me.com", "name", "joe")

我发现update_by_email中的kwargs

{'name': 'joe'}

这篇关于使用变量作为关键字传递给Python中的** kwargs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆