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,
Solution 1:
In Python 3.6, dictionaries are ordered internally, but this is considered an implementation detail which should not be relied upon.
In Python 3.7, dictionaries are ordered.
Therefore, you have 2 options:
Use the implementation detail at your risk
You can use list(d)
to retrieve the keys of the dictionary maintaining insertion order.
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
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']
Post a Comment for "How To Maintain The Order Of An Existing Dictionary Python"