在 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')

网址编码为:

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

我怎样才能让它编码为:

How can I get it to encode as:

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

I see that kwargs inside update_by_email is

{'name': 'joe'}