Converting Python Dict to Kwargs

Converting Python dict to kwargs?

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

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

is equivalent to

func(type='Event')

How can I pass a defined dictionary to **kwargs in Python?

There are 4 possible cases:

You call the function using named arguments and you want named variables in the function:

(note the default values)

def buy(orange=2, apple=3):
print('orange: ', orange)
print('apple: ', apple)

buy(apple=4)
# orange: 2
# apple: 4

You call the function using named arguments but you want a dictionary in the function:

then use **dictionaryname in the function definition to collect the passed arguments

def buy(**shoppinglist):
for name, qty in shoppinglist.items():
print('{}: {}'.format(name, qty) )

buy(apple=4, banana=5)
# banana: 5
# apple: 4

You call the function passing a dictionary but you want named variables in the function:

use **dictionaryname when calling the function to unpack the dictionary

def buy(icecream=1, apple=3, egg=1):
print('icecream:', icecream)
print('apple:', apple)
print('egg:', egg)

shoppinglist = {'icecream':5, 'apple':1}
buy(**shoppinglist)
# icecream: 5
# apple: 1
# egg: 1

You call the function passing a dictionary and you want a dictionary in the function:

just pass the dictionary

def buy(shoppinglist):
for name, qty in shoppinglist.items():
print('{}: {}'.format(name, qty) )

shoppinglist = {'egg':45, 'apple':1}
buy(shoppinglist)
# egg: 45
# apple: 1

How to send a dictionary to a function that accepts **kwargs?

Just use func(**some_dict) to call it.

This is documented on section 4.7.4 of python tutorial.

Note that the same dict is not passed into the function. A new copy is created, so some_dict is not kwargs.

how can I convert a dictionary to a string of keyword arguments?

The same syntax is used to accept arbitrary keyword arguments.

Python 2:

def somestring(**kwargs):
return ', '.join('%s=%r' % x for x in kwargs.iteritems())

Python 3:

def somestring(**kwargs):
return ", ".join(f"{key}={value}" for key, value in kwargs.items())

Note that dicts are arbitrarily ordered, so the resultant string may be in a different order than the arguments passed.

python dict parameter and or kwargs

I think the simplest solution is to merge the two dictionaries, then just use the get method on the result. If I understand your logic correctly (and I'm not sure I do...), you want the value of "passphrase_confirm" if it exists in one of the dictionaries, and if it doesn't, you want "passphrase". Also, if it's in both, you want the one from input_dict.

I think this does what you want, and is much easier to understand than your original code:

def get_passwd(input_dict=None, **kwargs):
kwargs = kwargs if input_dict is None else dict(kwargs.items() + input_dict.items())
if "passphrase_confirm" in kwargs:
return kwargs["passphrase_confirm"]
else:
return kwargs.get("passphrase", None)

Will dict(**kwargs) always give dictionary where Keys are of type string?

In the second case, the dict function accepts keyword arguments. And the keyword arguments can only be passed as string parameters.

Quoting the documentation,

Providing keyword arguments as in the first example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.

As long as the string is a valid python identifier, you can used that as a key in the second form. For example, the following will not work with the second form

>>> dict(1=2)
File "<input>", line 1
SyntaxError: keyword can't be an expression

But the same will work with the first form

>>> {1:2}
{1: 2}

How to properly pass a dict of key/value args to kwargs?

Use the **kw call convention:

f = Foo(**settings)

This works on any callable that takes keyword arguments:

def foo(spam='eggs', bar=None):
return spam, bar

arguments = {'spam': 'ham', 'bar': 'baz'}
print foo(**arguments)

or you could just call the function with keyword arguments:

f = Foo(foo="bar")
foo(spam='ham', bar='baz')

Your error is unrelated, you didn't define foo, you probably meant to make that a string:

settings = {'foo': 'bar'}


Related Topics



Leave a reply



Submit