为什么字典中的项目顺序在Python中更改? [英] Why items order in a dictionary changed in Python?
问题描述
>>> 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']
正如你在第一行中我可以看到我定义字典一样,项目pwd:secret
是字典中的最后一个元素。但是,当我输出字典时,它成为第一个元素。而且字典的其余部分已被重新排列。
我可以知道为什么会发生这种情况吗?
如果我使用dict.keys()从字典中提取密钥,并按照我认为是这样的顺序进行迭代,这会导致解决问题吗?
谢谢
我可以知道为什么会发生这种情况吗? b
这是因为内部组织的方式。
总之,这可以通过哈希-table根据它们的 hash()
值将密钥放入桶中。
如果我使用dict.keys()从字典中提取密钥,并按照我认为是这样的顺序进行迭代,那会引起解决问题吗?
取决于你的做法。
k = list(d.keys())
k.sort()
for i in k:print i,d [i]
应该完全按照你想要的方式工作。
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 dismatch problem?
Thank you very much.
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.
这篇关于为什么字典中的项目顺序在Python中更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!