【问题标题】:Understanding the ordering of a python dictionary了解python字典的顺序
【发布时间】:2020-11-02 06:11:57
【问题描述】:

谁能解释一下 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?
  • 我正在向learnpython.org 学习,所以我假设是最新的。所以v3.7?我将帖子标记为 3.x。
  • @Mech,我添加了一个答案,希望可以快速解决您的问题。
  • 不完全!您可以在其官方文档中查找每个新版本的更新。目前稳定版是3.8,很难找到好的教程。
  • 我没有足够的信心来发布我自己的答案,但目前缺少的答案是在较旧的 Python 版本中(在他们更改某些内容以保留插入顺序之前)存储的项目基于创建哈希表在键上,并使用该标准对项目进行排序。这样做是为了加快搜索速度:如果用户访问特定键,则计算哈希并完成二进制搜索。正如您所理解的,哈希值顺序可以不同于插入顺序或键字母顺序。我是这么理解的。

标签: python python-3.x loops for-loop


【解决方案1】:

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

在 Python 3.6 之前

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

Python 3.6+

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

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

Python 3.7

Guido van Rossum 在all Python implementations must preserve insertion order 中宣布了 Python 3.7 的字典。

【讨论】:

    【解决方案2】:

    与列表不同,存储在字典中的项目不按任何特定顺序保存;事实上,Python 将它们从左到右的顺序随机化以提供快速查找。键提供字典中项目的符号位置(非物理位置)。 如果您将列表视为对象的有序集合,则可以将字典视为无序集合。这些项目是通过键存储和获取的,而不是通过位置偏移量:)

    【讨论】:

      猜你喜欢
      • 2018-08-05
      • 1970-01-01
      • 1970-01-01
      • 2011-08-13
      • 2017-07-01
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多