为什么字典键顺序不同于创建它的字符串?

2024-10-03 23:18:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个字典,它将字母表中的所有字符作为键。我是这样做的:

import string

origAlphabetUpCase = string.ascii_uppercase
print origAlphabetUpCase

upCaseDict = dict((el,'') for el in origAlphabetUpCase)

结果如下:

ABCDEFGHIJKLMNOPQRSTUVWXYZ
{'A': '', 'C': '', 'B': '', 'E': '', 'D': '', 'G': '', 'F': '', 'I': '', 'H': '', 'K': '', 'J': '', 'M': '', 'L': '', 'O': '', 'N': '', 'Q': '', 'P': '', 'S': '', 'R': '', 'U': '', 'T': '', 'W': '', 'V': '', 'Y': '', 'X': '', 'Z': ''}

由于某些原因,键的顺序与初始字符串中的顺序不同。似乎字符对被交换了(除了AZ)。你知道吗

你知道为什么会这样吗?你知道吗


Tags: inimportforstring字典顺序ascii字符
3条回答

最好将字典看作一组无序的键:值对,要求键是唯一的(在一个字典中)。你知道吗

字典上的主要操作是用某个键存储一个值并提取给定键的值,实际上,在列表的什么时候插入哪个元素并不重要,它可能出现在列表的中间,也可能出现在列表的开头或结尾。给出的例子写在docs.python.org文件说

>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}

字典是可哈希元素的关键。由于字典使用哈希表来高效地查找键和这些键的值,因此没有对顺序进行排序。你知道吗

python中的集合也是无序的,因为集合中的元素是散列的,因此查找速度很快

if 'z' in ('x','y','z'):
  return 'z'

例如,如果它是一个列表['x','y','z'],那么它也会有一个O(1)的查找,而不是O(n)。你知道吗

下面来自python邮件列表的电子邮件详细讨论了python字典及其所做的哈希处理。你知道吗

https://mail.python.org/pipermail/python-list/2000-March/048085.html

Python字典没有任何顺序。你知道吗

docs

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

如果你读得更深入

The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the sorted() function to it).

所以您可以使用sorted函数或OrderedDict。你知道吗

相关问题 更多 >