Skip to main content
 首页 » 编程设计

python之Python字典中的整型键是否按优先级排序和排序

2025年05月04日16think

我在 OS X Mavericks 上使用 python 2.7.5,我发现我用来生成简单文本菜单的字典出现意外行为。我的问题是:Python 字典中的整数键是否按优先级排序和排序?我可以看到 mainMenu_1 字典(包含一些数字键和一些字符串键)排序整数键,然后以预期的随机顺序呈现字符串键。 mainMenu_2 按预期随机化。

来自 python 2.7.8 文档:

"It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary)."

mainMenu_1 = { 
   0: 'README', 
   1: 'New Set', 
   2: 'View Sets', 
   3: 'Quiz', 
   4: 'Scores', 
   5: 'Configuration Settings', 
   'Q': 'Quit', 
   'a': 'additional letter to test', 
   'b': 'additional letter to test' 
} 
 
mainMenu_2 = { 
   'one': 'README', 
   'two': 'New Set', 
   'three': 'View Sets', 
   'four': 'Quiz', 
   'five': 'Scores', 
   'six': 'Configuration Settings', 
   'Q': 'Quit', 
   'd': 'another letter to test' 
} 
 
print mainMenu_1.keys() 
[0, 1, 2, 3, 4, 5, 'a', 'Q', 'b'] 
print mainMenu_2.keys() 
['four', 'Q', 'five', 'three', 'd', 'six', 'two', 'one'] 

第三个测试:

c = {1:'one','two':'two',3:'three'} 
print c 
{1: 'one', 3: 'three', 'two': 'two'} 

请您参考如下方法:

dict 根据其底层哈希表桶“排序”(大量使用引号)。整数的 hash() 本身就是:

hash(42) 
Out[29]: 42 

...但这并不一定意味着较低的整数会出现在较高的整数之前,因为散列是采用模表大小以便将其分配给存储桶的。

d = {i:i for i in range(250,260)} 
 
print(d) 
{256: 256, 257: 257, 258: 258, 259: 259, 250: 250, 251: 251, 252: 252, 253: 253, 254: 254, 255: 255} 

所以连续的整数不一定在 dict 中排序。至于整数获得优先级,不,整数没有什么特别之处。它们的散列值特别好地聚集在一起,并且您碰巧选择了一些散列值比该团 block 更大(同样,模表大小)的字符串。

hash('roippi') 
Out[26]: 8915818834981308633 
 
hash('roippi') % 8 # min hashtable size in py2 is 3-bit 
Out[27]: 1 
 
d = {0:'', 'roippi':0, 2:0} 
 
print(d) 
{0: '', 'roippi': 0, 2: 0} 

当然所有这些都是cPython的实现细节,所以唯一可以保证的是排序是“任意但一致的1”。

1至少在 python 解释器的单次运行中是一致的。 3.2.3+ randomly seeds the hash某些(非整数)类型,如果使用 -R flag 运行,早期版本也会这样做.