On 06/20/11 00:32, TheSaint wrote: > Hello > > Trying to pop some key from a dict while is iterating over it will cause an > exception. > How I can remove items when the search result is true. > > Example: > > while len(dict): > for key in dict.keys(): > if dict[key] is not my_result: > dict.pop(key) > else: > condition_to_break > print('Dictionary is over')
Others has described how to do what you wanted to do, but let's address the main problem here, why are you iterating a dictionary? I found that most of the time that I thought I needed to iterate through a dictionary, it's really because I'm thinking the wrong way, and a little bit more thought lead me to a better way that doesn't involve iterating on the dictionary. While there are legitimate reasons for iterating a dictionary, I'd consider the alternatives first. -- http://mail.python.org/mailman/listinfo/python-list