Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Python dict to kwargs?

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

like image 768
teaforthecat Avatar asked Apr 19 '11 00:04

teaforthecat


People also ask

How do you pass a dict as Kwargs in Python?

“ kwargs ” stands for keyword arguments. It is used for passing advanced data objects like dictionaries to a function because in such functions one doesn't have a clue about the number of arguments, hence data passed is be dealt properly by adding “**” to the passing type.

How do you give Kwargs in Python?

The special syntax **kwargs in function definitions in python is used to pass a keyworded, variable-length argument list. We use the name kwargs with the double star. The reason is that the double star allows us to pass through keyword arguments (and any number of them).

What are Python Kwargs?

**kwargs allows us to pass a variable number of keyword arguments to a Python function. In the function, we use the double-asterisk ( ** ) before the parameter name to denote this type of argument.

How do I unpack a dictionary in Python?

The ** operator is used to pack and unpack dictionary in Python and is useful for sending them to a function.


2 Answers

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

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

is equivalent to

func(type='Event') 
like image 191
unutbu Avatar answered Sep 25 '22 20:09

unutbu


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

like image 34
Vishvajit Pathak Avatar answered Sep 26 '22 20:09

Vishvajit Pathak