Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python字典初始化_Python_Dictionary - Fatal编程技术网

Python字典初始化

Python字典初始化,python,dictionary,Python,Dictionary,我用以下键值对初始化了一个字典: count = {"a":0, "b":0, "c":0, "d":0, "e":0, "f":0, "g":0, "h":0, "i":0, "j":0, "k":0, "l":0, "m":0, "n":0, "o":0, "p":0, "q":0, "r": 0, "s":0, "t": 0, "u":0, "v":0, "w":0, "x":0, "y":0, "z":0} 然而,当我打印相同的内容时,除了第一个和最后一个之外,其他几对已经互换: {'

我用以下键值对初始化了一个字典:

count = {"a":0, "b":0, "c":0, "d":0, "e":0, "f":0, "g":0, "h":0, "i":0, "j":0, "k":0, "l":0, "m":0, "n":0, "o":0, "p":0, "q":0, "r": 0, "s":0, "t": 0, "u":0, "v":0, "w":0, "x":0, "y":0, "z":0}
然而,当我打印相同的内容时,除了第一个和最后一个之外,其他几对已经互换:

{'a': 0, 'c': 0, 'b': 0, 'e': 0, 'd': 0, 'g': 0, 'f': 0, 'i': 0, 'h': 0, 'k': 0, 'j': 0, 'm': 0, 'l': 0, 'o': 0, 'n': 0, 'q': 0, 'p': 0, 's': 0, 'r': 0, 'u': 0, 't': 0, 'w': 0, 'v': 0, 'y': 0, 'x': 0, 'z': 0}

这给了我试图解决的问题错误的答案。为什么会发生这种情况?

如果要保留顺序,则应使用collections.OrderedDitct而不是标准字典。

因为python字典是未排序的。除了python 3.6开始使用的以外ordered@trotta事情不再那么简单了。CPython 3.6作为一个实现细节,现在确实按照密钥最初插入的顺序(如
OrderedDict
)存储密钥。不仅仅是未排序:它们没有(保证)顺序。我相信Python3.6的顺序是一个实现细节,不值得依赖@Mihir94你能分享一些你试图解决的问题的细节吗?可能是
dict
不是最好的数据结构