Skip to content

Instantly share code, notes, and snippets.

@c51303
Created December 15, 2023 09:15
Show Gist options
  • Save c51303/218e3f602df159cc290d60d71b39f21a to your computer and use it in GitHub Desktop.
Save c51303/218e3f602df159cc290d60d71b39f21a to your computer and use it in GitHub Desktop.
RuntimeError: dictionary changed size during iteration

错误

 for key in dict.keys():
     if not dict[key]:
         del dict[key]

调整

for key in dict.copy().keys():
    if not dict[key]:
        del dict[key]

问题可能出在 字典在循环迭代中变更大小,因为字典是无序的。

  • The Python "RuntimeError: dictionary changed size during iteration" occurs when we change the size of a dictionary when iterating over it.
  • To solve the error, use the copy() method to create a shallow copy of the dictionary that you can iterate over, e.g., my_dict.copy().
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment