2011-07-21 51 views
1

我有一个整数作为键的字典。请告诉我,使用排序的键是否存储字典数据?应该按照公司的顺序存储密钥?

我写一些代码来测试(如下):

>>> 
>>> d = {1: 'a', 3: 'a'} 
>>> d 
{1: 'a', 3: 'a'} 
>>> d[2] = 'a' 
>>> d 
{1: 'a', 2: 'a', 3: 'a'} 
>>> 

但我不知道这种行为是标准和作品所有的时间。

+1

[Python:Element order in dictionary]的可能重复(http://stackoverflow.com/questions/5792190/python-element-order-in-dictionary) – Jacob

回答

4

python中的字典未排序。了解更多关于类型的字典在这里: http://docs.python.org/library/stdtypes.html?highlight=dict#dict

但是你可以用sorted python built-in method到按键排序:

for k in sorted(myDict): 
    myDict[k] # do something 

或者看看这里collections.OrderedDict implementation

你也可以混合排序方法和OrderedDict以后使用它(确定这只会在你不会添加新项目的情况下出现 - 否则它只是更好地使用排序方法):

d = {1: 'a', 3: 'a'} 
from collections import OrderedDict 
sorted_d = OrderedDict((k, d[k]) for k in sorted(d)) 
+1

只是为了说明所有'OrderedDict'都跟踪*键的顺序*。与保存键*排序*非常不同。 – mhyfritz

+0

谢谢@mhyfritz。 –

3

一点点运行实验会很快向您展示他们是没有排序:

>>> d = {1: 'a', 3: 'a', 8: 'a'} 
>>> d 
{8: 'a', 1: 'a', 3: 'a'} 

但即使是实现有关。不要依赖订单。