python - python字典中循环(for循环)的顺序是什么

标签 python dictionary for-loop

<分区>

我对从下面得到的输出有点困惑。 我不明白执行循环的顺序。

domains = { "de": "Germany", "sk": "Slovakia", "hu": "Hungary",
    "us": "United States", "no": "Norway"  }

for key in domains:
    print key

这里的输出是

sk
de
no
us
hu

但不是

de
sk
hu
us
no

同样,这里

num = {1:"one",4:"two",23:"three",10:"four"}
for key in num:
    print key
output is
1
10
4
23

但不是

1
4
23
10

感谢帮助

最佳答案

Python 词典 do not preserve ordering :

Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions

CPython 中的字典实现为 hash table启用快速查找和成员资格测试,并按照项目在该表中列出的顺序枚举键或值;它们被插入的位置取决于 key 的哈希值,以及之前是否有任何东西被哈希到同一个槽。

您必须在每次显示时对键进行排序,或者使用不同类型的数据结构来保持排序。 Python 2.7 或更新版本有一个 collections.OrderedDict()类型,或者您可以使用双值元组列表(此时查找单个键值对会很慢)。

关于python - python字典中循环(for循环)的顺序是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14445667/

相关文章:

python - 在 Python 中使用多个正则表达式或更大的正则表达式进行替换

ios - viewForAnnotation 没有被调用

python - "For item in list"循环,需要解释

windows - 循环语句的批处理文件

javascript - 运行 setTimeout 并更改时间值

Python Pandas 将字符串和数字连接成一个字符串

相当于列表中另一个的python项目

c++ - 使用 map::find 查找键并返回值

Python:从字典列表创建新字典

Python urllib2 登录 minecraft.net