there is a better way to clean up a dict?
<p>I have <code>dict</code>, say for example this</p>

<pre><code>data={k:k for k in range(20)}
</code></pre>

<p>I do some operation over the values of <code>data</code> and some of the en up as 0, for example this</p>

<pre><code>for k,v in data.items():
    data[k] %= 2
</code></pre>

<p>when doing this I want to remove all key that get a value of 0, but doing in the fly give a error so I have to do it in at the end, for that I do</p>

<pre><code>def clean(data):
    while True:
        try:
            for k,v in data.items():
                if not v:
                    del data[k]
            return
        except RuntimeError:
            pass
</code></pre>

<p>so my question is: there is a better way of doing this so I make the remotion <strong>in-place</strong> and avoiding using extra memory and better yet in one trip ??  </p>

<p><strong>EDIT</strong> </p>

<p>this is similar to my intended use</p>

<pre><code>class MapDict(dict):

    def __repr__(self):
        return '{}({})'.format(self.__class__.__qualname__, super().__repr__())

    def map(self,func,*argv):
        '''applicate func to every value in this MapDict'''
        for k,v in self.items():
            self[k] = func(v,*argv)
        self.clean()

    def clean(self):
        while True:
            try:
                for k,v in self.items():
                    if not v:
                        del self[k]
                return
            except RuntimeError:
                pass


&gt;&gt;&gt; data=MapDict( (k,k) for k in range(20) )
&gt;&gt;&gt; data
MapDict({0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 11: 11, 12: 12, 13: 13, 14: 14, 15: 15, 16: 16, 17: 17, 18: 18, 19: 19})
&gt;&gt;&gt; from operator import add, mod
&gt;&gt;&gt; data.map(mod,2)
&gt;&gt;&gt; data
MapDict({1: 1, 3: 1, 5: 1, 7: 1, 9: 1, 11: 1, 13: 1, 15: 1, 17: 1, 19: 1})
&gt;&gt;&gt; data.map(add,10)
&gt;&gt;&gt; data
MapDict({1: 11, 3: 11, 5: 11, 7: 11, 9: 11, 11: 11, 13: 11, 15: 11, 17: 11, 19: 11})
&gt;&gt;&gt; 
</code></pre>

<p>so that is why I could not make a new <code>dict</code>, and I want to only keep in my instance only the relevant values, that later I need to something else. </p>

<p>So is there a better way to do this clean? while keeping it memory efficient? and in the least amount of trip?</p>