【问题标题】:How to maintain the order of an existing dictionary python如何维护现有字典python的顺序
【发布时间】:2018-04-10 11:04:01
【问题描述】:

我创建了一个字典,稍后我想将它的值插入到一个列表中。我知道列表保持顺序,但我认为字典不是。我知道有 OrderedDict,但据我了解,它会在添加到字典时保持顺序。在这里,我已经有了完整的字典,没有添加。

我正在使用 python 3.6

我的脚本是:

dirs_dictionary = {"user_dir_treatment":"/home/dataset_1/treatment",
                           "user_dir_control":"/home/dataset_1/control"}

empty_list = []

for key, value in dirs_dictionary.items()):
    empty_list.append(dirs_dictionary[key])

所以最终,我希望列表包含的值与它们在字典中的顺序相同,这意味着列表中的第一项是"/home/dataset_1/treatment",第二项是"/home/dataset_1/control"

如何维护字典的顺序?

【问题讨论】:

  • 您使用的是哪个版本的 Python?不同版本的字典排序行为不同。
  • 我使用的是python 3.6.4版
  • 这个问题毫无意义。如果你不修改它,dict就不会改变它的顺序,那有什么问题呢?你必须什么都不做来维持它的秩序。但是,如果您打算修改 dict,请使用 OrderedDict。
  • 你可以使用 OrderedDict

标签: python python-3.x list dictionary


【解决方案1】:

在 Python 3.6 中,字典是内部排序的,但这被认为是一个实现细节,不应依赖它。

在 Python 3.7 中,字典是有序的。

因此,您有两个选择:

使用实施细节需要您自担风险

您可以使用list(d) 检索维护插入顺序的字典的键。

dirs_dictionary = {"user_dir_treatment":"/home/dataset_1/treatment",
                   "user_dir_control":"/home/dataset_1/control"}

empty_list = list(dirs_dictionary)

print(empty_list)

# ['user_dir_treatment', 'user_dir_control']

使用 OrderedDict

from collections import OrderedDict

dirs_dictionary = OrderedDict([("user_dir_treatment", "/home/dataset_1/treatment"),
                               ("user_dir_control", "/home/dataset_1/control")]

empty_list = list(dirs_dictionary)

print(empty_list)

# ['user_dir_treatment', 'user_dir_control']

【讨论】:

  • 非常感谢!只是为了确保我理解,第二个选项是保持订单最安全的选项,但在第一个选项中不确定订单是否会保持?
  • 抱歉,重复我的话。字典在 3.6 中是内部排序的 [阅读,“它可以工作”],但它被认为是 实现细节 [即你不应该在你的逻辑中使用这个事实]。第二种方式是3.6中的“正确”方法。
  • 感谢您的澄清!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-27
  • 2013-01-25
  • 2012-04-12
  • 2019-04-01
  • 2016-02-27
  • 2015-06-27
相关资源
最近更新 更多