为什么我的输出已经用python排序了

为什么我的输出已经用python排序了,python,dictionary,Python,Dictionary,下面代码的outout给出以下输出 prices = { "banana": 4, "apple": 2, "orange": 1.5, "pear": 3 } stock = { "banana": 6, "apple" : 0, "orange": 32, "pear": 15 } for item in prices: print item print "price: %s" % prices[item]

下面代码的outout给出以下输出

prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3
}
stock = {
    "banana": 6,
    "apple" : 0,
    "orange": 32,
    "pear": 15
}

for item in prices:
    print item
    print "price: %s" % prices[item]
    print "stock: %s" % stock[item]

我想问一下为什么它会以这种方式显示(按排序顺序)。香蕉不是应该先来,然后是苹果、橘子和梨吗?

它没有分类。您使用字典来存储数据。Python中的标准词典是无序的。它们基本上是连接到值的键的哈希映射。您看到的顺序是dict hashmap中键的顺序

无序字典最有可能实现为一个(事实上,Python明确指出了这一点),其中元素的顺序定义得很好,但并不明显。您的观察结果完全符合哈希表的规则:显然是任意的,但顺序不变


多亏@konrad rudolph

dict
不能保证排序,它基本上是一个

顺序基于
hash()
函数,您可以在解释器中检查:

orange
price: 1.5
stock: 32
pear
price: 3
stock: 15
banana
price: 4
stock: 6
apple
price: 2
stock: 0
None

Python
Dict
没有顺序。因此可以使用
OrderedDict

for item in sorted(prices.keys()):
     ...

在字典中搜索关于排序的无数其他副本。。。
for item in sorted(prices.keys()):
     ...
from collections import OrderedDict
for i, j in  OrderedDict(sorted(prices.items(), key=lambda x:x[1])).items():
    print i, j

orange 1.5
apple 2
pear 3
banana 4