In python, I wrote this function to teach myself how **kwargs
works in Python:
def fxn(a1, **kwargs):
print a1
for k in kwargs:
print k, " : ", kwargs[k]
I then called this function with
fxn(3, a2=2, a3=3, a4=4)
Here was the output that my Python interpreter printed:
3
a3 : 3
a2 : 2
a4 : 4
Why did the for loop print the value of a3 before that of a2 even though I fed a2 into my function first?
This has finally been introduced in the 3.6 release: dict
s are now ordered, therefore the keyword argument order is preserved.
Python 3.6.0 (default, Jan 13 2017, 13:27:48)
>>> def print_args(**kwargs):
... print(kwargs.keys())
...
>>> print_args(first=1, second=2, third=3)
dict_keys(['first', 'second', 'third'])
The unfortunate irony is that the dict-ification of **kwargs means that the following will not work (at least not the way one would expect):
od = OrderedDict(a=1, b=2, c=3)
Since the keyworded args are first built into an unordered dict, you cannot depend that they will be inserted into the OrderedDict in the order they are listed. :(
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