【发布时间】:2011-08-08 07:10:02
【问题描述】:
我想使用类继承为 sunburnt(solr 接口)构建一个查询,因此将键值对添加在一起。 sunburnt 接口采用关键字参数。如何将字典 ({'type':'Event'}) 转换为关键字参数 (type='Event')?
【问题讨论】:
标签: python dictionary keyword-argument
我想使用类继承为 sunburnt(solr 接口)构建一个查询,因此将键值对添加在一起。 sunburnt 接口采用关键字参数。如何将字典 ({'type':'Event'}) 转换为关键字参数 (type='Event')?
【问题讨论】:
标签: python dictionary keyword-argument
【讨论】:
func(**myDict)。即myDict = {"type": "event"}
** 运算符在这里会有所帮助。
** 运算符将解压 dict 元素,因此 **{'type':'Event'} 将被视为 type='Event'
func(**{'type':'Event'}) 与 func(type='Event') 相同,即 dict 元素将转换为 keyword arguments。
仅供参考
* 将解包列表元素,它们将被视为positional arguments。
func(*['one', 'two']) 与func('one', 'two') 相同
【讨论】:
这是一个完整的示例,展示了如何使用 ** 运算符将字典中的值作为关键字参数传递。
>>> 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
【讨论】: