How to iterate on a changing dictionary

Lie Ryan lie.1296 at gmail.com
Sun Jun 19 13:00:27 EDT 2011


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.



More information about the Python-list mailing list