理解python字典的排序

Mec*_*ech 2 python loops for-loop python-3.x

有人可以解释一下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.")
Run Code Online (Sandbox Code Playgroud)

实际输出:

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.
Run Code Online (Sandbox Code Playgroud)

预期输出(字典的顺序):

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.
Run Code Online (Sandbox Code Playgroud)

lmi*_*asf 8

这取决于您使用的 Python 版本。

在 Python 3.6 之前

字典使用底层散列函数的顺序。有几种类型具有加盐哈希,因此这意味着您在每次调用时获得不同的顺序。

蟒蛇 3.6+

字典是按插入顺序排列的,即字典记住插入项的顺序。从文档

这个新实现的顺序保留方面被认为是一个实现细节,不应依赖

蟒蛇 3.7

Guido van Rossum 宣布从 Python 3.7 开始,所有 Python 实现中的字典都必须保留插入顺序