使用变量作为关键字传递给Python中的**kwargs

Jos*_*osh 4 python arguments keyword kwargs

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

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

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

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)
Run Code Online (Sandbox Code Playgroud)

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

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

该网址编码为:

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

先感谢您.

jon*_*rpe 7

field您可以使用字典解包来使用 field作为参数的名称,而不是传递名为的参数:

request = update_by_email(email, **{field: field_value})
Run Code Online (Sandbox Code Playgroud)

使用模拟update_by_email:

def update_by_email(email=None, **kwargs):
    print(kwargs)
Run Code Online (Sandbox Code Playgroud)

我打电话的时候

update_field("joe@me.com", "name", "joe")
Run Code Online (Sandbox Code Playgroud)

我看到kwargs里面update_by_email

{'name': 'joe'}
Run Code Online (Sandbox Code Playgroud)