gpt4 book ai didi

python - 了解 python 字典的顺序

转载 作者:行者123 更新时间:2023-12-05 08:50:02 25 4
gpt4 key购买 nike

谁能解释一下 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.

最佳答案

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

Python 3.6 之前

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

Python 3.6+

字典是按插入顺序排列的,即字典会记住插入项目的顺序。来自 the docs :

The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon

python 3.7

Guido van Rossum 在 all Python implementations must preserve insertion order 中宣布从 Python 3.7 开始.

关于python - 了解 python 字典的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62869237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com