0

I have text files in a directory with data. I am looking at populating a dict with keys being the name of the text files, and the corresponding items containing the data of the files. I would like the order of the name keys in the dict to reflect the order of creation of the test files in the repertory. The code I used is:

date_file_list = []
for filename in files:
    stats = os.stat(filename)
    lastmod_date = time.localtime(stats[8])
    date_file_tuple = lastmod_date, filename
    date_file_list.append(date_file_tuple) 
date_file_list.sort()
date_file_list_array = np.asarray(date_file_list)
File2Array = {}
for filename in date_file_list_array[0:20,1]:
    print(filename)
    File2Array.setdefault(filename,OpenandReadOO(filename))

OpenandReadOO is a python function that open and read the file with name filename and fill a numpy array.

Unfortunately, even if list date_file_list and date_file_list_array are correctly ordered, when iterating through them (seemingly in the right order), the resulting dict is always not ordered.

How should I proceed to obtain a dict with items (and data) in the correct order?

Thanks

Greg

gregory
  • 413
  • 4
  • 12
  • 1
    You can't. Python's dictionary is inherently unordered. Use `collections.OrderedDict` instead and take a look at the first answer of this question: http://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key – StefanS May 15 '17 at 06:55

1 Answers1

0

You should use ordered dict:

from collections import OrderedDict

res = OrderedDict()

for filename in date_file_list_array[0:20,1]:
    print(filename)
    res.__setitem__(filename,OpenandReadOO(filename))
mohammad
  • 2,232
  • 1
  • 18
  • 38