I have a piece of python code, which need to iterator over all keys in a dictionary where the body of the loop might change the dictionary.
Just trying to iterator over the dictionary give me
RuntimeError: dictionary changed size during iteration. Searching for the error message lead me to another question, where the suggested solution was to copy the list of keys before starting the iteration.
In my scenario that is however only a partial answer, because I need to iterate over not only the original keys but also over keys that are added while I am iterating. I need code that only terminates once no more keys are being added to the dictionary, and it has processed any keys already in the dictionary.
So far I have come up with this:
processed = set() while True: keys = set(dictionary) - processed if not keys: break for k in keys: processed.add(k) # Do something with k
This approach does seem overly complicated. Is there any way I could simplify it, and still have it process all of the keys being added to the dictionary without processing each of them more than once?
In some other languages the first four lines of the while loop could have been written simply as:
while keys = set(dictionary) - processed:
However that doesn't work in python. I found a question about using an assignment as condition in a while loop in python. But none of the proposed answers seem applicable to my scenario.