我对从下面得到的输出有点困惑。
我不明白执行循环的顺序。
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()
类型,或者您可以使用双值元组列表(此时查找单个键值对会很慢)。