有人能解释一下python (v3.5)字典是如何订购的吗?
data = {"John": 23, "Rick": 33, "Mary": 63, "Ron": 23, "Joel": 51}
for key in data:
print("Your name is " + key + ", and you are also " + str(data[key]) + " years old.")实际产出:
Your name is Rick, and you are also 33 years old.
Your name is Ron, and you are also 23 years old.
Your name is Mary, and you are also 63 years old.
Your name is John, and you are also 23 years old.
Your name is Joel, and you are also 51 years old.预期输出(字典的顺序):
Your name is John, and you are also 23 years old.
Your name is Rick, and you are also 33 years old.
Your name is Mary, and you are also 63 years old.
Your name is Ron, and you are also 23 years old.
Your name is Joel, and you are also 51 years old.发布于 2020-07-13 04:30:24
这取决于您正在使用的Python版本。
在Python 3.6之前
字典使用底层哈希函数的排序。有几种类型有盐散列,因此这意味着每次调用都有不同的顺序。
Python 3.6+
字典是按插入顺序排列的,也就是说,字典记住插入项的顺序。来自医生们
这个新实现的保持顺序的方面被认为是一个实现细节,不应该依赖它。
Python 3.7
Guido宣布了所有Python实现都必须保持插入顺序。中Python3.7dicts的内容。
发布于 2020-07-13 04:33:01
与列表中不同的是,字典中存储的项没有按任何特定的顺序保存;事实上,Python将它们从左到右的顺序随机化,以提供快速查找。键提供字典中项的符号位置(而不是物理位置)。如果在列表中将对象视为有序集合,则可以将字典视为无序集合。这些项由键来存储和获取,而不是通过位置偏移:)
https://stackoverflow.com/questions/62869237
复制相似问题