Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why items order in a dictionary changed in Python? [duplicate]

I am trying to learn Python from some tutorial. Here is a simple example I encountered that puzzles me.

>>> d={"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}

>>> d
{'pwd': 'secret', 'database': 'master', 'uid': 'sa', 'server': 'mpilgrim'}

>>> d.keys()
['pwd', 'database', 'uid', 'server']

>>> d.values()
['secret', 'master', 'sa', 'mpilgrim']

As you can see in the first line where I define the dictionary, the item "pwd":"secret" is the last element in the dictionary. However, when I output the dictionary, it became the first element. And the rest part of the dictionary has been reordered.

May I know why this is happening?

If I use dict.keys() to extract the keys from a dictionary and iterate it in an order that I suppose it to be, will that cause mismatch problem?

like image 326
ChangeMyName Avatar asked Nov 25 '13 12:11

ChangeMyName


1 Answers

May I know why this is happening?

It is because of the way dicts are organized internally.

In short, this works via a hash-table which puts the keys into buckets according to their hash() value.

If I use dict.keys() to extract the keys from a dictionary and iterate it in an order that I suppose it to be, will that cause dismatch problem?

Depending on how you do it.

k = list(d.keys())
k.sort()
for i in k: print i, d[i]

should exactly work how you want it to work.

like image 115
glglgl Avatar answered Nov 02 '22 07:11

glglgl