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"?
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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With