根据python中文件的创建日期排序dict键
我在一个包含数据的目录中有文本文件。我正在研究用键填充dict,键是文本文件的名称,以及包含文件数据的相应项。 我希望dict中名称键的顺序能够反映保留库中测试文件的创建顺序。我使用的代码 是: OpenandReadOO是一个python函数,用于打开和读取名为filename的文件,并填充numpy数组 不幸的是,即使list date\u file\u list和date\u file\u list\u数组的顺序正确,当遍历它们时(看起来顺序正确),生成的dict始终没有顺序 我应该如何按照正确的顺序获取包含项目(和数据)的dict 谢谢根据python中文件的创建日期排序dict键,python,dictionary,Python,Dictionary,我在一个包含数据的目录中有文本文件。我正在研究用键填充dict,键是文本文件的名称,以及包含文件数据的相应项。 我希望dict中名称键的顺序能够反映保留库中测试文件的创建顺序。我使用的代码 是: OpenandReadOO是一个python函数,用于打开和读取名为filename的文件,并填充numpy数组 不幸的是,即使list date\u file\u list和date\u file\u list\u数组的顺序正确,当遍历它们时(看起来顺序正确),生成的dict始终没有顺序 我应该如何按
Greg您应该使用有序dict:
from collections import OrderedDict
res = OrderedDict()
for filename in date_file_list_array[0:20,1]:
print(filename)
res.__setitem__(filename,OpenandReadOO(filename))
你不能。Python的字典本质上是无序的。改用collections.OrderedDict,看看这个问题的第一个答案:它工作得很好,谢谢。
from collections import OrderedDict
res = OrderedDict()
for filename in date_file_list_array[0:20,1]:
print(filename)
res.__setitem__(filename,OpenandReadOO(filename))