Iterating over dict and removing some elements

superpollo utente at esempio.net
Tue May 11 11:26:29 EDT 2010


superpollo ha scritto:
> Ulrich Eckhardt ha scritto:
>> Hi!
>>
>> I wrote a simple loop like this:
>>
>>   d = {}
>>   ...
>>   for k in d:
>>       if some_condition(d[k]):
>>           d.pop(k)
>>
>> If I run this, Python complains that the dictionary size changed during
>> iteration. I understand that the iterator relies on the internal 
>> structure
>> not changing, but how would I structure this loop otherwise?
> 
> my first thought (untested):
> 
> use a copy of d for the if clause, then pop from the original.
> 
> bye

i mean:

 >>> d = {"name":"max","surname":"zanardi","nick":"zanna"}
 >>> dc = copy.copy(d)
 >>> dc
{'nick': 'zanna', 'surname': 'zanardi', 'name': 'max'}
 >>> for k in dc:
...     if dc[k].startswith("z"):
...         d.pop(k)
...
'zanna'
'zanardi'
 >>> d
{'name': 'max'}
 >>> dc
{'nick': 'zanna', 'surname': 'zanardi', 'name': 'max'}
 >>>

bye



More information about the Python-list mailing list