From an external file I generate the following dictionary:
mydict = { 'foo' : 123, 'bar' : 456 }
Given a function that takes a **kwargs
argument, how can generate the keyword-args from that dictionary?
The ** unpacking operator can be used to pass kwargs from one function to another function's kwargs. Consider this code: (newlines don't seem to be allowed in comments) def a(**kw): print(kw) , and def b(**kw): a(kw) .
Unpacking kwargs and dictionaries You cannot directly send a dictionary as a parameter to a function accepting kwargs. The dictionary must be unpacked so that the function may make use of its elements. This is done by unpacking the dictionary, by placing ** before the dictionary name as you pass it into the function.
kwargs is variable name used for keyword arguments, another variable name can be used. The important part is that it's a dictionary and it's unpacked with the double asterisk operator ** . Other iterables are unpacked with the single asterisk operator *
In Python, keyword arguments(kwargs) are values that are accessed by specific parameters in a function. A keyword argument is followed by a parameter and the assignment operator (=). In Python, keyword arguments can be passed through dictionaries.
def foo(**kwargs):
pass
foo(**{ 'foo' : 123, 'bar' : 456 })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With