How to iterate on a changing dictionary

Terry Reedy tjreedy at udel.edu
Sun Jun 19 12:02:12 EDT 2011


On 6/19/2011 11:13 AM, Chris Angelico wrote:
> 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.

The other is to make a set of to_be_deleted keys and delete them all 
when done.

If you only want to delete one key, break the iteration and then delete.

> 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.



-- 
Terry Jan Reedy




More information about the Python-list mailing list