dict: retrieve the original key by key
Ian Kelly
ian.g.kelly at gmail.com
Sun May 15 20:47:45 EDT 2011
On Sun, May 15, 2011 at 4:18 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Sun, 15 May 2011 11:11:41 +0200, Christoph Groth wrote:
>
>> I would like to avoid having _multiple_ objects which are equal (a == b)
>> but not the same (a is not b). This would save a lot of memory.
>
> Based on the idea of interning, which is used for Python strings:
>
> cache = {}
> def my_intern(obj):
> return cache.setdefault(obj, obj)
And if the idea of a dictionary with identical keys and values
offends, you can also use a set:
cache = set()
def my_intern(obj):
cache.add(obj)
return cache.intersection([obj]).pop()
Cheers,
Ian
More information about the Python-list
mailing list