使用 for 循环打印字典中的条目

Using a for loop to print entries within a dictionary

为什么会出现以下程序:

tokens = {
    'Apple': 1,
    'Orange': 2,
    'Pear': 3,
    'Banana': 4,
}

for t in tokens:
    print t, 'corresponds to', tokens[t]

产生以下输出:

Orange corresponds to 2
Pear corresponds to 3
Apple corresponds to 1
Banana corresponds to 4

换句话说,为什么它打印第2个条目,然后第3个,然后第1个,然后第4个?即为什么它不从第一个条目打印到最后一个条目?

来自python documentation entry for dict

"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."

那是因为 dict 是作为哈希函数实现的,它将键映射到任意排序但确定的列表

任意 因为(1)散列函数没有记录,(2)映射到列表中相同条目的散列将(可能)根据它们的插入顺序排序;

确定性 这样你总是能得到相同的值。

字典未排序,您不妨使用 OrderedDict.

这会记住您添加密钥的顺序。

from collections import OrderedDict
tokens = OrderedDict()

tokens['Apple'] = 1
tokens['Orange'] = 2
tokens['Pear'] = 3
tokens['Banana'] = 4

对于 jlb83 的回答,如果您不想使用 OrderedDict,您可以循环遍历键的有序列表。

tokens = {
    'Apple': 1,
    'Orange': 2,
    'Pear': 3,
    'Banana': 4,
}

for t in sorted(tokens.keys()):
    print t, 'corresponds to', tokens[t]

产生以下输出

Apple corresponds to 1
Banana corresponds to 4
Orange corresponds to 2
Pear corresponds to 3

我敢肯定可以通过多种方式进行排序,但这确实有效。