463

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


See also: What do ** (double star/asterisk) and * (star/asterisk) mean in a function call? - the corresponding question for people who encounter the syntax and are confused by it.

1

3 Answers 3

825

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

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

is equivalent to

func(type='Event')
3
  • 115
    and if you already have a dict object called "myDict" you just func(**myDict) .i.e myDict = {"type": "event"} Apr 19, 2011 at 0:57
  • 3
    This is pretty well-covered in the python standard documentation. See also: stackoverflow.com/questions/1137161. (dmid://juice_cobra_hush)
    – dreftymac
    Feb 29, 2016 at 23:17
  • 1
    This is brilliantly helpful, especially when using converting dictionaries into Swagger model instances. Thanks.
    – timmins
    Feb 21, 2019 at 22:59
49

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

17

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.