问题:将Python字典转换为kwargs?

我想使用类继承构建一个针对sunburnt(solr interface)的查询,因此将键-值对加在一起。sunburnt接口带有关键字参数。如何将字典({'type':'Event'})转换为关键字参数(type='Event')

I want to build a query for sunburnt(solr interface) using class inheritance and therefore adding key – value pairs together. The sunburnt interface takes keyword arguments. How can I transform a dict ({'type':'Event'}) into keyword arguments (type='Event')?


回答 0

使用双星运算符(又名double-splat?):

func(**{'type':'Event'})

相当于

func(type='Event')

Use the double-star (aka double-splat?) operator:

func(**{'type':'Event'})

is equivalent to

func(type='Event')

回答 1

** 操作员在这里会有所帮助。

**操作员将解开dict元素的包装,因此**{'type':'Event'}将被视为type='Event'

func(**{'type':'Event'}) 与…相同 func(type='Event') dict元素将转换为相同keyword arguments

费耶

* 将解压缩列表元素,它们将被视为 positional arguments

func(*['one', 'two']) 与…相同 func('one', 'two')

** operator would be helpful here.

** operator will unpack the dict elements and thus **{'type':'Event'} would be treated as type='Event'

func(**{'type':'Event'}) is same as func(type='Event') i.e the dict elements would be converted to the keyword arguments.

FYI

* will unpack the list elements and they would be treated as positional arguments.

func(*['one', 'two']) is same as func('one', 'two')


回答 2

这是一个完整的示例,显示了如何使用**运算符将字典中的值作为关键字参数传递。

>>> def f(x=2):
...     print(x)
... 
>>> new_x = {'x': 4}
>>> f()        #    default value x=2
2
>>> f(x=3)     #   explicit value x=3
3
>>> f(**new_x) # dictionary value x=4 
4

Here is a complete example showing how to use the ** operator to pass values from a dictionary as keyword arguments.

>>> def f(x=2):
...     print(x)
... 
>>> new_x = {'x': 4}
>>> f()        #    default value x=2
2
>>> f(x=3)     #   explicit value x=3
3
>>> f(**new_x) # dictionary value x=4 
4

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。