我在OS X Mavericks上使用python 2.7.5,并且看到字典用于生成简单文本菜单的行为异常。我的问题是:Python字典中的整数键是否按优先级排序和排序? 我可以看到mainMenu_1
字典(包含一些数字键和一些字符串键)对整数键进行排序,然后以预期的随机顺序显示字符串键。mainMenu_2
按预期随机化。
来自python 2.7.8 docs:
“最好将字典视为一组无序的键:值对,要求键是唯一的(在一个字典中)。”
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']
Run Code Online (Sandbox Code Playgroud)
第三项测试:
c = {1:'one','two':'two',3:'three'}
print c
{1: 'one', 3: 'three', 'two': 'two'}
Run Code Online (Sandbox Code Playgroud)
dict
会根据其基础哈希表存储区对它们进行“排序”(大量使用引号)。该hash()
整数本身是:
hash(42)
Out[29]: 42
Run Code Online (Sandbox Code Playgroud)
...但是这并不一定意味着较低的整数会在较高的整数之前出现,因为哈希值是对表大小取模的,以便将其分配给存储桶。
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}
Run Code Online (Sandbox Code Playgroud)
因此,连续整数不必在中排序dict
。至于获得优先级的整数,不,关于整数没有什么特别的。它们的哈希值特别好地聚集在一起,并且您碰巧选择了一些散列比该聚集更大的字符串(再次是表的模数)。
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}
Run Code Online (Sandbox Code Playgroud)
当然,所有这些都是cPython的实现细节,因此唯一可以保证的是排序是“任意但一致的1 ”。
1至少在一次python解释器运行中保持一致。3.2.3+ 随机地播种某些(非int)类型的哈希值,并且如果使用-R标志运行,则较早的版本也会这样做。