Home > Software design >  Why can't I modify the dict's value in place while iterating its keys?
Why can't I modify the dict's value in place while iterating its keys?

Time:02-24

    for id in my_dict.keys():
        try:
            if id in my_map:
                my_dict[my_map[id]] = my_dict[id]
        except Exception as e:
         pass

I received an modification while iteration error. I am only iterating the keys. Is that equal to iterating the whole dict?

CodePudding user response:

Your current code has a few problems:

  • You're modifying an iterable (the dictionary) while iterating over it. That's the immediate error you're hitting; modifying an iterable during an iteration will generally invalidate the iteration, and may lead to obvious or non-obvious errors.
  • id is a builtin function; don't use it as a variable name.
  • Don't get in the habit of catching and swallowing exceptions. If you don't expect your code to raise an exception, it's generally better to let it raise if you're wrong (so that you can discover your error more quickly). If you expect it to raise an exception, catch that specific Exception in an intentional way.

The easier approach to what you're trying is to build a dict with all the keys you want to add/update, and then update your dict with it:

my_dict.update({my_map[k]: v for k, v in my_dict.items() if k in my_map})

CodePudding user response:

Is not possible inside a loop because you change the size of the dict. Use .copy and use a copy of this dicr

  • Related