How to iterate on a changing dictionary
Terry Reedy
tjreedy at udel.edu
Sun Jun 19 12:51:06 EDT 2011
On 6/19/2011 11:53 AM, Roy Smith wrote:
> Yet another variation which makes sense if you want to delete most of
> the keys would be to copy them to a new dictionary. I'm not sure how
> Python handles memory management on dictionaries which shrink.
'Python' does not handle memory management; each implementation does -).
I believe CPython will shrink lists and dicts that are too empty, but it
should be both more efficient and more dependable to make a new one as
with your code or
old_d = {i:i for i in range(100)}
d = {key:val for key,val in old_d.items() if not key%13}
d
>>>
{0: 0, 65: 65, 39: 39, 13: 13, 78: 78, 52: 52, 26: 26, 91: 91}
--
Terry Jan Reedy
More information about the Python-list
mailing list