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

How to pop from a dict while looping?

I have a following problem. I have a dictionary dict_a. I would like to go through it and if some condition is met, then I would like to pop the item from the dict_a. When I try this:

for key in dict_a.keys():
     if # some condition:
         dict_a.pop(key)            

I got an error

RuntimeError: dictionary changed size during iteration. 

Is there a more pythonic way how to do it than this below?

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

dict_b = dict_a.copy()

for key in dict_a.keys():
     if # some condition:
         dict_b.pop(key)  

dict_a = dict_b.copy()

>Solution :

You could make a list from dict_a keys beforehand:

for key in list(dict_a):
     if # some condition:
         dict_a.pop(key)
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