Solved

RuntimeError: dictionary changed size during iteration

OliviaPyOP

I'm removing inactive crew members while looping over the dict and get this error.

2

Comments 4

Log in to join the discussion.

Log in Create account
  1. SophieDev Solutionreplies: 1

    You can't add or remove keys while iterating over the same dict. Iterate over a copy of the keys, or build a new dict:

    for name in list(crew):
        if not crew[name]["active"]:
            del crew[name]
    # or
    crew = {n: d for n, d in crew.items() if d["active"]}
    8
    1. OliviaPyOP

      The comprehension version is really clean, going with that.

      0
    2. TomBecker

      Changing values while iterating is fine, it's only adding/removing keys that breaks it.

      3
      1. LucasVD

        Same applies to lists, except lists don't warn you — they just skip elements silently. Even worse!

        0