Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

    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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading