I have a dict that has millions of elements, and can use hundreds of megabytes of memory.
I want to remove certain elements, based on a condition on the key:
d = {k: k for k in range(10_000_000)} # simplified example
def mycondition(x):
return x % 10 != 0 # simplified
This will work, but it will do a new copy of the dict, so I'd like to avoid it:
d = {k: v for k, v in d.items() if mycondition(k)}because it would use the double of the RAM than needed compared to an "in place" solution
This fails:
for k, v in d.items(): if not mycondition(k): del d[k]because
RuntimeError: dictionary changed size during iteration
How to solve this problem "in place", i.e. without using twice the size of d in RAM?