Rayne Rayne - 6 months ago 28
Python Question

Iterate through a dictionary in reverse order (Python)

I understand that when iterating through a dictionary, it will be in arbitrary order. However, I need to make sure that one particular item is accessed last, and this item happens to have the smallest key. How should I implement this?

Right now, I have

files["h"] = DIRECTORY["h"][0]
files["n"] = DIRECTORY["n"][0]
files["a"] = DIRECTORY["a"][0]

for key, file_dir in files.iteritems():
print ("Checking {0} in {1}".format(key, file_dir))
# process files


The dictionary happens to be iterated in the order "a", "h", "n". I need to process "a" last because it's dependent on the files in "h" and "n".

Is there a way to do this without running the
process files
code twice, once for "h" and "n", another for "a"?

Answer

You can create an ordered dictionary, and then you could accomplish what you're trying to do:

from collections import OrderedDict

files = OrderedDict()
files["h"] = DIRECTORY["h"][0]
files["n"] = DIRECTORY["n"][0]
files["a"] = DIRECTORY["a"][0]

for key, file_dir in files.iteritems():
    print ("Checking {0} in {1}".format(key, file_dir))