How to delete an entry from a dictionary in Python?

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

Was this solution helpful to you?

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:

Just Added Q & A:

Find solution

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.