Why items order in a dictionary changed in Python?

2020-02-01 08:37发布

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?

7条回答
仙女界的扛把子
2楼-- · 2020-02-01 09:19

If you want to maintain the insertion order, you can use OrderedDict. But regular dict objects store the values by hashing the key and using that for lookups, which doesn't keep the order, but makes lookup faster.

查看更多
登录 后发表回答