Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, what determines the order while iterating through kwargs?

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?

like image 834
dangerChihuahua007 Avatar asked Jan 23 '12 19:01

dangerChihuahua007


2 Answers

This has finally been introduced in the 3.6 release: dicts 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'])
like image 131
afxentios Avatar answered Nov 16 '22 03:11

afxentios


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. :(

like image 45
PaulMcG Avatar answered Nov 16 '22 03:11

PaulMcG