Dealing With “Dictionary Changed Size During Iteration” In Python When Modifying a dict In-Place

The aim of this playbook🏁 is to idiomatically deal with Runtime Error: Dictionary changed size during iteration when modifying a dictionary in-place within a for a loop.


  • pass the items into a list constructor that creates an on-the-fly-list just for the loop
for key, _ in list(imgIndex.items()):
if docID in key:
del imgIndex[key]