Working in Python, how can I delete items while iterating over a dictionary?
-
Got runtime error if call "del dict[key]" during iterating - RuntimeError: dictionary changed size during iteration
-
Answer:
for key,value in my_dict.items(): if key == "delete": my_dict.pop(key) this works because my_dict.items() returns a new list of key,value tuples ... if you just needed keys you could just do my_dict.keys() but you never want to modify an object while iterating over it with for i in some_object #avoid modifying some_object at all costs pass #ok now that we are not iterating it we can modify
Joran Beasley at Quora Visit the source
Other answers
Its better not to delete items from any iterable while iterating. Instead, use comprehension and filtering whenever possible. So, the code becomes like this {key:my_dict[key] for key in my_dict if key != "deleted"} This is called Dictionary comprehension. This creates a new dictionary without the item where the key is "deleted". This is preferred most of the times. If you are worried about memory consumption, you can make the old reference point to the newly constructed dictionary, like this my_dict = {k:my_dict[k] for k in my_dict if k != "deleted"} This makes sure that reference count of the old dictionary reduce by 1. If there are no other references to that old dictionary, then it will be ready for garbage collection.
Sakthipriyan Vairamani
Related Q & A:
- How can I delete a myyearbook account?Best solution by Yahoo! Answers
- How can I delete a messenger group?Best solution by Yahoo! Answers
- How can I delete a former e-mail address?Best solution by Yahoo! Answers
- How can I delete a folder that I created in Yahoo mail?Best solution by Yahoo! Answers
- How can I delete my all mails at a time?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.