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')?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Use the double-star (aka double-splat?) operator:
func(**{'type':'Event'})
is equivalent to
func(type='Event')
Method 2
** 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')
Method 3
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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0