How do I get a reference to a KEY value of a dictionary?

Aahz aahz at
Sat Aug 2 16:16:13 CEST 2003

In article <w1MWa.133$Tz4.17019035 at>,
Andy C <ayc8NOSPAM at> wrote:
>I don't see how I can do this and let me eliminate duplicates.  I need
>to assign the old duplicate string to the unique string that already
>exists.  Hence the question, how do I get a reference to the KEY value?
>I know I can use keys() and do a linear search, but that is much more
>inefficient.  I would like to get a reference to the key value in the
>same time that it takes to do a hash lookup (constant time).

Ahhhh....  Right.  Hmmmmm....  <thinks hard>  You're correct, you do
need to set the value to the key.  I think using a dict is better than
using intern().  Here's an optimization:

    node2 = node_cache.setdefault(node2, node2)

>The intern solution seems reasonable, and it appears that it was
>designed specifically for this problem.  I wasn't aware of the
>implementation problems.  But I'm still curious about different ways to
>do it.

intern() is intended more for a small-scale optimization of
frequently-used strings rather than as a mechanism for memory
Aahz (aahz at           <*>

This is Python.  We don't care much about theory, except where it intersects 
with useful practice.  --Aahz

More information about the Python-list mailing list