CSnerd
CSnerd

Reputation: 2229

The order of print when use items() in python

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?

Upvotes: 1

Views: 78

Answers (2)

volcano
volcano

Reputation: 3582

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.

Upvotes: 2

Christian Tapia
Christian Tapia

Reputation: 34146

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'>

Upvotes: 5

Related Questions