Qn: Nested dictionary cleanup
Peter Otten
__peter__ at web.de
Mon Nov 3 17:02:19 EST 2003
Colin Brown wrote:
> My code fragment below:
>
> for key1 in dict1.keys():
> for key2 in dict1[key1]:
> if dict1[key1][key2] == None:
> del dict1[key1][key2]
>
> gives the following error:
> RuntimeError: dictionary changed size during iteration
>
> Any suggestion on how to code this please.
>
> Thanks
> Colin Brown
> PyNZ
In addition to Emile van Sebille's fix, the following tries to avoid
dictionary lookups:
# dict1 is not changed so we need not copy the values
for innerdict in dict1.itervalues():
# innerdict is changed so let's make a copy of the items
for key, value in innerdict.items():
if value is None:
del innerdict[key]
Peter
More information about the Python-list
mailing list