简体   繁体   中英

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

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.

I can't tell if the code you're giving is pseudo-code or not, but if that's the actual code an the key you actually want to be last is a then it might be as simple as:

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

for key, file_dir in sorted(files.iteritems(), key=lambda x: 1 if x[0] == 'a' else 0):
    print ("Checking {0} in {1}".format(key, file_dir))
    # process files

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM