I have dict
, say for example this
data={k:k for k in range(20)}
I do some operation over the values of data
and some of the en up as 0, for example this
for k,v in data.items():
data[k] %= 2
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
def clean(data):
while True:
try:
for k,v in data.items():
if not v:
del data[k]
return
except RuntimeError:
pass
so my question is: there is a better way of doing this so I make the remotion in-place and avoiding using extra memory and better yet in one trip ??
EDIT
this is similar to my intended use
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
>>> data=MapDict( (k,k) for k in range(20) )
>>> 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})
>>> from operator import add, mod
>>> data.map(mod,2)
>>> data
MapDict({1: 1, 3: 1, 5: 1, 7: 1, 9: 1, 11: 1, 13: 1, 15: 1, 17: 1, 19: 1})
>>> data.map(add,10)
>>> data
MapDict({1: 11, 3: 11, 5: 11, 7: 11, 9: 11, 11: 11, 13: 11, 15: 11, 17: 11, 19: 11})
>>>
so that is why I could not make a new dict
, and I want to only keep in my instance only the relevant values, that later I need to something else.
So is there a better way to do this clean? while keeping it memory efficient? and in the least amount of trip?