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

Pavol Kutaj
Sep 11, 2021

--

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.

notes

  • pass the items into a list constructor that creates an on-the-fly-list just for the loop
  • modify in-place
  • I am deleting a key in place in a structure loaded from a YAML file that will be later replace the same file
for key, _ in list(imgIndex.items()):
if docID in key:
del imgIndex[key]

links

--

--

No responses yet