Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"?

like image 955
Rayne Avatar asked May 23 '16 02:05

Rayne


2 Answers

Just sort the list before iterating on them.

for key, file_dir in sorted(files.iteritems(), key=lambda x:x[0].lower, reverse=True):
    print ("Checking {0} in {1}".format(key, file_dir))

For python 3, since iteritems() was removed.

files = {"d":2, "g":1, "a":3, "b":3, "t":2}
print(files.items())
for key, file_dir in sorted(list(files.items()), key=lambda x:x[0].lower(), reverse=True):
    print ("Checking {0} in {1}".format(key, file_dir))
like image 192
mattsap Avatar answered Sep 21 '22 13:09

mattsap


Arbitrary means "outside your control". You can't make the dictionary give you anything first or last or otherwise control what order it gives you items in. If you want that one last, sort the items and then iterate over the sorted list. Or, if that one item is unique and you want to handle it differently, pop that one out of the dictionary and handle it separately at the end.

like image 22
BrenBarn Avatar answered Sep 25 '22 13:09

BrenBarn