简体   繁体   English

如何维护现有字典python的顺序

[英]How to maintain the order of an existing dictionary python

I created a dictionary, and later I'd like in insert it's values to a list. 我创建了一个字典,后来我想将其值插入到列表中。 I know that lists keep their order, but I think that dictionaries are not. 我知道列表保持顺序,但我认为字典不是。 I know there is OrderedDict, but from what I understand it keeps the order upon addition to the dictionary. 我知道有OrderedDict,但是据我了解,它在添加到字典中时保持顺序。 Here, I have already the complete dictionary, without adding to it. 在这里,我已经有完整的字典,没有添加。

I'm using python 3.6 我正在使用python 3.6

My script is: 我的脚本是:

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])

So eventually, I'd like that the list will contain the values in the same order as they are in the dictionary, meaning that the first item in the list is "/home/dataset_1/treatment" , and the second is "/home/dataset_1/control" . 所以最终,我希望列表包含的值与字典中的顺序相同,这意味着列表中的第一项是"/home/dataset_1/treatment" ,第二项是"/home/dataset_1/control"

How do I maintain the order of my dictionary? 如何维护字典的顺序?

In Python 3.6, dictionaries are ordered internally, but this is considered an implementation detail which should not be relied upon. 在Python 3.6中,字典在内部进行排序,但这被视为实现细节 ,不应依赖于它。

In Python 3.7, dictionaries are ordered. 在Python 3.7中,字典是有序的。

Therefore, you have 2 options: 因此,您有2个选择:

Use the implementation detail at your risk 使用实施细节需要您自担风险

You can use list(d) to retrieve the keys of the dictionary maintaining insertion order. 您可以使用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']

Use OrderedDict 使用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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM