1

I write a function like this in python:

def test(**argv):
    for k,v in argv.items():
        print k,v

and use the function like this:

test(x = 1, y=2, z=3)

The printout is this:

y 2
x 1
z 3

I was wondering why the result of printout is not?:

x 1
y 2
z 3

Any help here?

CSnerd
  • 2,129
  • 8
  • 22
  • 45
  • possible duplicate of [In Python, what determines the order while iterating through kwargs?](http://stackoverflow.com/questions/8977594/in-python-what-determines-the-order-while-iterating-through-kwargs) – jonrsharpe Jan 05 '14 at 14:58
  • @ jonrsharpe whoops, sorry what should I do now? – CSnerd Jan 05 '14 at 15:00
  • Read the linked question, delete yours if you agree it's answered there, otherwise wait for the community to vote to decide what should happen. See http://stackoverflow.com/help/duplicates – jonrsharpe Jan 05 '14 at 15:03
  • @jonrsharpe It says that Sorry, this question has answers and cannot be deleted; flag it for moderator attention instead – CSnerd Jan 05 '14 at 15:11
  • Ok, just wait and see! – jonrsharpe Jan 05 '14 at 15:12

2 Answers2

5

If you print the type of argv, you will realize it is a dictionary.

Dictionaries are unordered in Python. That's why you get that output.

Test

def test(**argv):
    print type(argv)

test()

>>> <type 'dict'>
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
2

Dictionary is a hash table, the order of the keys is not guaranteed. You you need to preserve the order - there is collections.OrderedDict, which preserves the order of element addition.

Tom Leese
  • 19,309
  • 12
  • 45
  • 70
volcano
  • 3,578
  • 21
  • 28
  • Can you make `**kwargs` use OrderedDict? I think you'd need a post-hoc `sort` – jonrsharpe Jan 05 '14 at 14:49
  • @jonrsharpe Correct. You can sort the key value pairs, but even that way you can't retrieve the order the keyword arguments were written out at the call site. –  Jan 05 '14 at 14:54
  • @jonrsharpe, yep, the order is not preserved if ordered dictionary is passed as keyword argument. – volcano Jan 05 '14 at 15:49