How to iterate on a changing dictionary

Chris Angelico rosuav at gmail.com
Sun Jun 19 11:13:58 EDT 2011


On Mon, Jun 20, 2011 at 12:32 AM, TheSaint <nobody at nowhere.net.no> 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')

One way is to iterate over an explicitly formed list of the keys.

for key in list(dict.keys()):

That creates an entirely new list with a snapshot copy of the keys. If
you then remove elements from the dictionary, the list will still
iterate correctly.

I'm not sure what you're trying to do, but you may find it easier to
use the 'filter' function (which takes an iterable, so possibly use
dict.iteritems() for that).It'll keep some and not others, and then
you can make use of just the ones you get back.

Chris Angelico



More information about the Python-list mailing list