dict.reserve and other tricks

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Fri Nov 17 02:51:36 EST 2006


Thank you for the answers Terry Reedy and Klaas.

> Since you are writing extensions, you can create a built-in subclass of
> dict to experiment with.  I presume the 2.5 default dict should be a model.

That way it's doable, but I think it's of limited use too; I'd like to
remove elements from arbitrary (normal) dicts.


Klaas:

> Well, you can reduce the memory usage to virtually nothing by using a
> generator expression rather than list comprehension.

Are you sure? I don't think so. Can you show a little example?
As you know this can't work:

def filterdict(pred, indict):
  todel = (k for k,v in indict.iteritems() if not pred(k,v))
  for key in todel:
    del indict[key]

d = dict.fromkeys(xrange(8), 0)
print d
filterdict(lambda k,v: k & 1, d)
print d

(You can remove elements from the dict and put  them into a list, and
then put back the elements into the dict, this is probably the only way
I know of *theoretically* keeping the memory used about  the same with
Python. In practice the less memory consuming version may be the
filterdict I have shown).


> arbitrary python code can be executed by __hash__
> and deleting (DECREF) python objects.

I am starting to understand. I'll think more about this.

Thank you,
bye,
bearophile




More information about the Python-list mailing list