我想创建一个字典,它将字母表中的所有字符作为键。我是这样做的:
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': ''}
由于某些原因,键的顺序与初始字符串中的顺序不同。似乎字符对被交换了(除了A
和Z
)。你知道吗
你知道为什么会这样吗?你知道吗
最好将字典看作一组无序的键:值对,要求键是唯一的(在一个字典中)。你知道吗
字典上的主要操作是用某个键存储一个值并提取给定键的值,实际上,在列表的什么时候插入哪个元素并不重要,它可能出现在列表的中间,也可能出现在列表的开头或结尾。给出的例子写在docs.python.org文件说
字典是可哈希元素的关键。由于字典使用哈希表来高效地查找键和这些键的值,因此没有对顺序进行排序。你知道吗
python中的集合也是无序的,因为集合中的元素是散列的,因此查找速度很快
例如,如果它是一个列表
['x','y','z']
,那么它也会有一个O(1)
的查找,而不是O(n)
。你知道吗下面来自python邮件列表的电子邮件详细讨论了python字典及其所做的哈希处理。你知道吗
https://mail.python.org/pipermail/python-list/2000-March/048085.html
Python字典没有任何顺序。你知道吗
从docs:
如果你读得更深入
所以您可以使用sorted函数或OrderedDict。你知道吗
相关问题 更多 >
编程相关推荐