How do I get a reference to a KEY value of a dictionary?
John Machin
sjmachin at lexicon.net
Tue Aug 5 20:33:46 EDT 2003
aahz at pythoncraft.com (Aahz) wrote in message news:<bgoh3r$knm$1 at panix1.panix.com>...
> In article <jyFXa.342$TC.22669471 at newssvr13.news.prodigy.com>,
> Andy C <ayc8NOSPAM at cornell.edu> wrote:
> >
> >OK, you're right -- I assumed that the key and value were duplicated,
> >but that's not the case. I don't know why I thought that, maybe since
> >the key must be immutable and the value is mutable. So I guess having
> >a dictionary of the form { 'A': 'A', 'B': 'B' } is not as stupid as it
> >first seems, since only a reference is stored. But still I wonder why
> >the language doesn't have a facility for getting a reference to the key
> >value in constant time. Apparently someone did it by modifying the C
> >source for the dictionary to add a ref_key() accessor. It seems like
> >it would be useful quite often.
>
> Well, you're the first person I recall caring about this specific issue.
> Of course, general caching issues come up quite frequently. All the
> people I've seen wanting to use intern() come at it from a performance
> rather than memory perspective, for which a dict would be no use. ;-)
Human recall can be defective, or input-deficient. I say again:
Google("intern-like memory saver") (in this news group).
As I said in that thread, when you run out of physical memory and you
start to access your swapfile, you have a performance problem.
As far as a dict being of no use, in my case I *already* have a dict,
which is used for frequency counting, and the algorithm being used
wants to maintain all of its data in memory as well. Thus being able
to get a reference to the frequency dict key and store that in the
data structure is a major win.
These days I have an extension which merely subclasses dict to add on
a key reference method and an increment method which does something
like:
def increment(self, key):
if key in self:
self[key] += 1
else:
self[key] = 1
Regards,
"someone"
More information about the Python-list
mailing list