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

John Machin sjmachin at lexicon.net
Sat Aug 2 19:16:16 EDT 2003


"Andy C" <ayc8NOSPAM at cornell.edu> wrote in message news:<w1MWa.133$Tz4.17019035 at newssvr21.news.prodigy.com>...
> 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).
> 
> Basically I would want to rewrite this section of the code I posted:
> 
>         nodes = self.nodes
>         if nodes.has_key( node2 ):
>             node2 = nodes[ node2 ]
>         else:
>             nodes[ node2 ] = node2
> 
> This dictionary seems stupid, I agree.  The keys and values are the same.
> But in the first part of the if, I want to reassign node2 to an equivalent
> string that already exists.  How can I do that?
> 
> 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.
> 

Google("intern-like memory saver").




More information about the Python-list mailing list