Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #5452

Re: dict: retrieve the original key by key

References <874o4wwenu.fsf@falma.de> <BANLkTikszH_r-PAuL0pJ8reMc+bGafuRew@mail.gmail.com> <mailman.1584.1305450715.9059.python-list@python.org> <4dcfa885$0$29996$c3e8da3$5496439d@news.astraweb.com>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2011-05-15 18:47 -0600
Subject Re: dict: retrieve the original key by key
Newsgroups comp.lang.python
Message-ID <mailman.1606.1305506896.9059.python-list@python.org> (permalink)

Show all headers | View raw


On Sun, May 15, 2011 at 4:18 AM, Steven D'Aprano
<steve+comp.lang.python@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

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

Re: dict: retrieve the original key by key Christoph Groth <cwg@falma.de> - 2011-05-15 11:11 +0200
  Re: dict: retrieve the original key by key Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-05-15 10:18 +0000
    Re: dict: retrieve the original key by key Christoph Groth <cwg@falma.de> - 2011-05-15 12:46 +0200
    Re: dict: retrieve the original key by key Terry Reedy <tjreedy@udel.edu> - 2011-05-15 16:53 -0400
    Re: dict: retrieve the original key by key Chris Rebert <clp2@rebertia.com> - 2011-05-15 14:19 -0700
    Re: dict: retrieve the original key by key Ian Kelly <ian.g.kelly@gmail.com> - 2011-05-15 18:47 -0600

csiph-web