python - OrderedDict 不保留顺序

标签 python dictionary ordereddictionary

from collections import OrderedDict
import pprint

menu = {"about" : "about", "login" : "login", 'signup': "signup"}

menu = OrderedDict(menu)
pprint.pprint(menu.items())

import sys
sys.exit()

输出是:

[('about', 'about'), ('signup', 'signup'), ('login', 'login')]

因此,即使使用 OrderedDict 也不会保留顺序。我知道字典默认情况下不保留初始顺序,以及所有这些东西。但我想了解为什么 OrderedDict 不起作用。

最佳答案

通过将项目放入(无序的)dict 并从中构建 OrderedDict,您已经丢弃了原始顺序。从元组列表而不是字典构造 OrderedDict。

关于python - OrderedDict 不保留顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26232936/

相关文章:

python - 如何自定义排序 Pandas 多索引?

python - 使用 NumPy Unicode 数组,为什么 dtype '|U5' 变成 dtype '<U5' ?

python - 使用 python 如何在文本文件的选择行中插入字符串,其中插入的字符串取决于行的内容和已知的映射?

python - 如何在python中的字典中获取键的位置

python-2.7 - 切片Python OrderedDict

python - Pandas :在约束下对每对列应用函数

python - opencv - 将像素从 bgr 转换为 hsv

dictionary - 我什么时候会使用 mapc 而不是 mapcar?

c# - 如何从子词典中获取子元素列表?

python - 如何在 python OrderedDict 上使用字符串键而不是整数进行切片?